An Interest In:
Web News this Week
- March 6, 2024
- March 5, 2024
- March 4, 2024
- March 3, 2024
- March 2, 2024
- March 1, 2024
- February 29, 2024
September 5, 2022 02:26 pm GMT
Original Link: https://dev.to/urstrulyvishwak/js-functional-composition-15dc
Javascript: Functional Composition
It is an approach where result of one function passed on to next function.
const add = (x, y) => x+y;const subtract = (x) => x-4;const multiply = (x) => x * 8;// result of `add` is passed to `subtract` and its result passed to `multiply`.const result = multiply(subtract(add(2, 3)));result;> 8
That looks readable but what if we have more functions to call one after other.
Let's try little cleaner approach.
const compose = (...functions) => x => functions.reduceRight((total, f) => f(total), x);const add = x => x+2;const subtract = x => x-1;const multiply = x => x * 8;compose(multiply, subtract, add)(2);> 24
We can also use reduce to implement:
const pipe = (...functions) => x => functions.reduce((total, f) => f(total), x);const add = x => x+2;const subtract = x => x-1;const multiply = x => x * 8;pipe(add, subtract, multiply)(2);> 24
pipe
- performs from left-to-right.compose
- performs from right-to-left.
Original Link: https://dev.to/urstrulyvishwak/js-functional-composition-15dc
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To