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
9Explanation
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
Editorial: Function Composition
Right to left
compose([f, g, h])(x) is f(g(h(x))) — the last function in the array sees the input first. That ordering comes from mathematics, where f ∘ g means apply g then f.
Approach
It is a fold from the right, starting at the input value.
Implementation
function compose(functions) { return (x) => functions.reduceRight((acc, fn) => fn(acc), x); }
Worth knowing
The empty case falls out for free: with no functions, reduceRight returns the initial value, which is the input unchanged.
Reverse the direction and you have pipe, which many codebases prefer precisely because it reads in execution order. Knowing why both exist is usually the follow-up.
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it