DEV Community 👩‍💻👨‍💻

Cover image for How To Make compose() and pipe() In Javascript
Fahim Zada
Fahim Zada

Posted on

How To Make compose() and pipe() In Javascript

Hi there,
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.

It is a mechanism for combining functions, in which the output of each function is passed into the next one, and the output of the last function is the final result. Applicable to every programming language, not just JavaScript.

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.

Compose

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
Enter fullscreen mode Exit fullscreen mode

Pipe

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

🌚 Life is too short to browse without dark mode