Function Composition

Higher-Order FunctionsFunctional

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

Example 1
Input
const fn = compose([(x) => x + 1, (x) => x * 2]);
fn(4);
Output
9
Explanation
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.

Hints

Read the full write-up for Function Composition
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it