Skip to main content

Command Palette

Search for a command to run...

Function Composition and Pipe

How to apply functional chain and pipe in javascript.

Updated
โ€ขView as Markdown
Function Composition and Pipe
K

๐Ÿ‘‹ Hi, I'm kanhaiya.

I'm a Software Engineer. I write up about JavaScript, React and other web technologies.

Suppose we have two functions and we want to call these functions to get result by calling these two functions. A situation like this.

carbon.png

Seems like a lot of code right. Suppose we have to call more than 5 functions to get a result it would take a whole day to write the code. Is there any solution to this problem?

Yes!

We can use function composition to reduce a lot of code. Now, what is function composition?

Since one function output is used in another function as input we can chain it and call. And this is what function composition is. Function composition is the process of combining two or more functions to produce a new function. Composing functions together is like snapping together a series of pipes for our data to flow through.

Put simply, a composition of functions f and g can be defined as f(g(x)), which evaluates from the inside out โ€” right to left. In other words, the evaluation order is:

  • x
  • g
  • f

Let us see how we can do this.

carbon (1).png

But here as you can see there is one problem if we've to call more than 2 functions we've to pass all the functions as parameters as well as call in the same order. A pure headache . Can we reduce it anyway?

We can reduce this code a little bit more and make it more optimized and generic by using ReduceRight. Now if you don't know what reduceRight is I'll suggest to go this link and look at how it works. MDN

Let's understand the code now.

carbon (2).png

On the other hand, if we want to reverse the order of the function invocation so that it will make it easy to read as we humans imagine it in our minds.

This process is called Pipe. You can understand in this way that when a plumber attaches one pipe on the back of another pipe to make way.

Code will be similar to the previous compose function, except that it will use reduce instead of the reduceRight method. To know how reduce works in JS click here.

carbon (3).png

This makes more sense.

In conclusion, function composition enables reusability of functionality at a very high level. If the functions are structured well it enables developers to created new behavior based upon existing behavior.

It also increases the readability of implementations. Instead of nesting functionswe can clearly chain functions and create higher-order functions with meaningful names.