The most encountered situation while building a complex functionality is where we need to pass a value to the function, and the return (result) value is required input for another function . It might sound okay if you have 2 - 3 functions, but when you have more than that, your code becomes messy and non-readable. To solve this issue, here comes the function composition.
We can do it in two different ways. However, one thing to keep in mind is that the sequence matter, and it will change your final result.
Passing your functions in the right to left order for execution. Example (f4,f3,f2,f1 )
//Compose function using reduceRight() const compose = (...args) => (value) => args.reduceRight((prev, fn) => fn(prev), value); // Increment the passed value by 2 const increment = (n) => n + 2; // Triples the passed value const double = (n) => n * 3; //Divide it by 2 const divide = (n) => n / 2; // Using our composition function console.log(compose(divide, double, increment)(2)); // 6
Passing your functions in the left to right order for execution. Example (f1,f2,f3,f4 )
//pipe function using reduce(), default left to right execution const pipe = (...args) => (value) => args.reduce((prev, fn) => fn(prev), value); // Increment the passed value by 2 const increment = (n) => n + 2; // Triples the passed value const double = (n) => n * 3; //Divide it by 2 const divide = (n) => n / 2; // Using our pipe function console.log(pipe(increment, double, divide)(3)); // 7.5
Tip: As already mentioned, the sequence matters, so you can create only a compose function and use it as a pipe by passing your functions in left to right order.
Thanks for reading.