Skip to content

Instantly share code, notes, and snippets.

@bhaveshdaswani93
Last active December 29, 2019 13:14
Show Gist options
  • Save bhaveshdaswani93/3fe00d71b93ef0f55fb02321f057be4d to your computer and use it in GitHub Desktop.
Save bhaveshdaswani93/3fe00d71b93ef0f55fb02321f057be4d to your computer and use it in GitHub Desktop.
Let's understand compose and pipe with an example
// Our task is to multiply a number with 3 and take absolute of that number
const multiplyWith3 = (x)=>x*3;
const getAbsouleOfNum = (x)=>Math.abs(x)
// here we have two component multiplyWith3 and getAbsouleOfNum
// if we want to do that without compose we will do like these
let x = 15;
let xAfterMultiply = multiplyWith3(x);
let xAfterAbsoulte = getAbsouleOfNum(xAfterMultiply);
//Let's do in composable way
const compose = (f,g) => data=>f(g(data));
const multiplyBy3andGetAbsolute = compose(multiplyWith3,getAbsouleOfNum);
multiplyBy3andGetAbsolute(-15) //45
// Here we have two components multiplyBy3 and getAbsoulteOfNum, we created a realtion between them that is output of absolute function
// will be input for multiply by 3 function using compose.
//Let's do in Pipe fashion
const pipe = (f,g) => data=>g(f(data));
const multiplyBy3andGetAbsolutePipe = pipe(multiplyWith3,getAbsouleOfNum);
multiplyBy3andGetAbsolutePipe(-15) //45
// Pipe is similar to compose but difference is that the flow is from left to right in pipe while in compose it is from right to left
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment