Compose Functions Right to Left
Write compose(functions) that folds the array into one function. Calling the result with a value feeds that value to the last function first, then passes each output leftwards to the function before it.
So compose([a, b, c])(v) means a(b(c(v))). With no functions at all, the result simply hands back whatever it was called with.
Examples
const fn = compose([(x) => x * 10, (x) => x - 1]);
fn(5);40Constraints
- Each function takes one value and returns one value
- The array may be empty
Notes
- Reverse the direction and you have `pipe`, which many codebases prefer because it reads in execution order.
Hints
Editorial: Compose Functions Right to Left
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.