Function Composition
MediumFunctional Programming15 min4 tests
Implement a compose function that takes multiple functions and returns a new function that applies them right-to-left.
Requirements
compose(f, g, h)(x)should equalf(g(h(x)))- Should work with any number of functions
- With no functions, return the identity function
Example
const add1 = x => x + 1;
const double = x => x * 2;
compose(add1, double)(5); // 11 (double first: 10, then add1: 11)Hints (3)
- Use
reduceRightto apply functions from right to left. - The initial value of the reduce is the input argument.
- Handle the edge case of zero functions passed.
Topics
- Functional Programming
Asked at
Meta · Stripe · Airbnb
