Piping Function
What is a piping function ?
The result of one function will be the argument of another function.
Normal code --->
const val ={
salary:10000
}
const getSalary =(person)=> person.salary;
const addBonus = (netSalary)=>netSalary+1000;
const deductTax=(grossSalary) =>{
const percentDeduction =grossSalary * 0.3
return grossSalary - percentDeduction
}
const pipe = (getSalary,addBonus,deductTax)=>{
return (val)=>{
const person=val;
const netSalary=getSalary(person);
const grossSalary =addBonus(netSalary);
const CreditSalary = deductTax(grossSalary);
return CreditSalary;
}
}
const result =pipe(getSalary,addBonus,deductTax)(val);
console.log(result)
PIPING CODE
const val ={ salary:10000 } const getSalary =(person)=> person.salary; const addBonus = (netSalary)=>netSalary+1000; const deductTax=(grossSalary) =>grossSalary - (grossSalary * 0.3)
const pipe = (...fns)=>{ return (val)=>{ fns.forEach((fn)=> val=fn(val)) return val; } } const result =pipe(getSalary,addBonus,deductTax)(val); console.log(result)
const obj ={
a:{
b: (a,b,c)=> a+b+c,
c: (a,b,c)=> a+b-c,
},
d :(a,b,c)=> a-b-c
}
const pipe =(obj)=>{
return (...args)=>{
for( let key in obj){
let val =obj[key];
if(typeof val==='function'){
obj[key] =val(...args);
}
else{
obj[key]= pipe(val)(...args)
}
}
return obj;
}
}
console.log(pipe(obj)(1,1,1));
Comments
Post a Comment