Function Composition
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
const fn = compose([(x) => x + 1, (x) => x * 2]);
fn(4);9Constraints
- 0 <= functions.length <= 1000
Notes
- Reverse the direction and you have `pipe`, which many codebases prefer because it reads in execution order.
Hints
Function Composition (reference solution)
One way to do it. The Editorial tab walks through why it is written this way.
Solution
1function compose(functions) {
2 return (x) => functions.reduceRight((acc, fn) => fn(acc), x);
3}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.