Compose Functions Right to Left

Higher-Order FunctionsFunctional

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

Example 1
Input
const fn = compose([(x) => x * 10, (x) => x - 1]);
fn(5);
Output
40
Explanation
The rightmost function runs first: 5 minus 1 is 4, and 4 times 10 is 40. Running them left to right would have given 49.

Constraints

  • 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

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