Loading problem…
Implement compose, a functional programming utility that chains multiple unary functions into a single pipeline, executing them sequentially from right to left.
Composition is deeply preferred over monolithic object inheritance because it allows developers to snap together tiny, predictable, and pure functional transforms. Knowing how to reduce an array of functions into a single closure is a fundamental functional programming pattern.
Implement the chain manufacturer:
function compose(functions) {}It should accept an array of functions and return a new function that encapsulates the sequence pipeline.
compose([f, g, h])(x), the execution sequence is f(g(h(x))).functions is entirely empty, return the mathematical identity function—a function that simply passes whatever argument it receives directly back unchanged (e.g., x => x).const add1 = (x) => x + 1;
const double = (x) => x * 2;
const subtract3 = (x) => x - 3;
const pipeline = compose([add1, double, subtract3]);
// Execution: add1(double(subtract3(5)))
// 1. subtract3(5) -> 2
// 2. double(2) -> 4
// 3. add1(4) -> 5
console.log(pipeline(5)); // 5