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 `multip…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Mahesh

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.


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Mahesh


Print Share Comment Cite Upload Translate Updates
APA

Mahesh | Sciencx (2022-09-05T14:26:49+00:00) Javascript: Functional Composition. Retrieved from https://www.scien.cx/2022/09/05/javascript-functional-composition/

MLA
" » Javascript: Functional Composition." Mahesh | Sciencx - Monday September 5, 2022, https://www.scien.cx/2022/09/05/javascript-functional-composition/
HARVARD
Mahesh | Sciencx Monday September 5, 2022 » Javascript: Functional Composition., viewed ,<https://www.scien.cx/2022/09/05/javascript-functional-composition/>
VANCOUVER
Mahesh | Sciencx - » Javascript: Functional Composition. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/09/05/javascript-functional-composition/
CHICAGO
" » Javascript: Functional Composition." Mahesh | Sciencx - Accessed . https://www.scien.cx/2022/09/05/javascript-functional-composition/
IEEE
" » Javascript: Functional Composition." Mahesh | Sciencx [Online]. Available: https://www.scien.cx/2022/09/05/javascript-functional-composition/. [Accessed: ]
rf:citation
» Javascript: Functional Composition | Mahesh | Sciencx | https://www.scien.cx/2022/09/05/javascript-functional-composition/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.