Compose and pipe in JavaScript

Function composition is an operation that takes two functions a and b and produces a function h such that h(x) = a(b(x)).

Compose Function

const compose = (a, b) => (data) => a(b(data));
const multiplyBy5 = (num) => num * 5;
const makePositive = (num) => Math.abs(num);

const multiplyBy5andMakePositive = compose(multiplyBy5, makePositive);
console.log(multiplyBy5andMakePositive(-50));
250

The definition compose ability is a system design principle that deals with the relationship between components.

With compose functions, you can build them together to add extra functionality to create that data flow where we take a piece of data we take it through all these functions and them finally we have some sort of data that gets output because all the functions are pure and all the functions are composed of all.

Pipe Function

const pipe = (a, b) => (data) => b(a(data));
const multiplyBy5 = (num) => num * 5;
const makePositive = (num) => Math.abs(num);

const multiplyBy5andMakePositive = pipe(multiplyBy5, makePositive);
console.log(multiplyBy5andMakePositive(-50));
250

Pipe function order is b(a(data)), but Compose function order is a(b(data)). this is just swap the props.

More functions with compose and pipe

Firstly right function argument is executed: compose

Firstly left function argument is executed: pipe

Leave a Reply

Your email address will not be published.

ANOTE.DEV