DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on • Edited on

6 2

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

pipe - performs from left-to-right.
compose - performs from right-to-left.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs