#Higher-Order Functions#Functional

Function Composition

Fold an array of functions into one, applied right to left.

By Pratik RaiEasy

Write compose(functions) returning a single function f where f(x) applies each function from right to left.

compose([f, g, h])(x) is f(g(h(x))). An empty array gives a function that returns its input unchanged.

Examples

Input:

JSfile.javascript
1const fn = compose([(x) => x + 1, (x) => x * 2]); 2fn(4);

Output:

9

The rightmost function runs first: 4 doubled is 8, then incremented is 9.

Constraints

  • 0 <= functions.length <= 1000

Notes

  • Reverse the direction and you have pipe, which many codebases prefer because it reads in execution order.

Goal: Return one function that applies the whole array right to left.

Source

Frequently asked questions

What is function composition?
Combining several functions into one, where the output of each becomes the input of the next. `compose([f, g])(x)` is `f(g(x))`.
Why does compose run right to left?
It follows mathematical notation, where `f ∘ g` means apply `g` first. Reversing the direction gives `pipe`, which many codebases prefer because it reads in the order things happen.
What should compose return for an empty array?
The identity function — one that returns its input unchanged. Using `reduceRight` with the input as the initial value gives that without a special case.
Where is composition used in real code?
Redux middleware and `applyMiddleware` are built on it, as are most functional utility libraries. It also underpins how a chain of transformations is expressed without nesting calls twenty levels deep.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Allow One Function Call

A once wrapper: the first call runs, every call after it does nothing.

JavaScript · ES6Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6Pratik Rai ·

JavaScript

Memoize

Cache a function by its arguments so the same call never computes twice.

JavaScript · ES6Pratik Rai ·