compose

Medium · Functional Programming Concepts · 2 test cases

Implement a `compose` function that takes two functions, f and g, and returns a new function that is the composition of f and g (i.e., f(g(x))).

Examples

const add5 = x => x + 5;
const double = x => x * 2;
const add5ThenDouble = compose(double, add5);
add5ThenDouble(10) → 30

Starter code

function compose(f, g) {

}

Complexity of the optimal solution

Time O(T(f) + T(g)), space O(1). The compose function itself runs in constant time. When the returned function is called, its execution time is the sum of the execution times of the composed functions, f and g. The space complexity refers to the compose function itself, which is constant.

Solve compose in the browser