Composition is the idea that any sort of data transformation that we do should be obvious. Compose does not exist in JS, so we have to use outside library like Ramda.
It's kind of like a conveyor belt right in a factory. It's easy to move pieces around to get the desired output based on the user's specific requirements.
// Compose function that do two things: // multiply by three and make abosulte value.constcompose= (f, g) => data =>f(g(data)); // our own created compose functionconstmultiplyBy3= num => num *3;constreturnAbsoluteNumber= num =>Math.abs(num);constmultiplyBy3AndAbsolute=compose( multiplyBy3, returnAbsoluteNumber );console.log(multiplyBy3AndAbsolute(-50));
Pipe is similar to compose, but different flow.
fn1(fn2(fn3(50))); //Create compose and pipe:compose(fn1, fn2, fn3)(50); //Right to left//same aspipe(fn3, fn2, fn1)(50); //left to rightconstcompose= (f, g) => data =>f(g(data));constpipe= (f, g) => data =>g(f(data));
Compose and pipe function that can take many arguments
constcompose= (...fns) =>fns.reduce((f, g) => (...args) =>f(g(...args)));constpipe= (...fns) =>fns.reduceRight((f, g) => (...args) =>f(g(...args)));//Exampleconstcompose= (...fns) =>fns.reduce((f, g) => (...args) =>f(g(...args)));constmultiplyBy3= num => num *3;constreturnAbsoluteNumber= num =>Math.abs(num);constshowTwoDecimalPlace= num =>parseFloat(Math.round(num *100) /100).toFixed(2);constmyFunction=compose( showTwoDecimalPlace, returnAbsoluteNumber , multiplyBy3);console.log(myFunction(-50)); // 150.00
With compose and pipe, we've created our little assembly line where we can compose different functions together and they can be assembled in various combinations, these tiny little functions can be easily tested, they are pure functions and at the same time, we're able to compose them together to do something more complex.