FrontendInterviews.dev

Loading problem…

159. Compose Function

Easy•

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.

Requirements

Implement the chain manufacturer:

function compose(functions) {}

It should accept an array of functions and return a new function that encapsulates the sequence pipeline.

Pipeline Semantics

  • Executions flow strictly right-to-left. Given compose([f, g, h])(x), the execution sequence is f(g(h(x))).
  • You may assume all functions in this variant are completely synchronous transforms.
  • The accumulated output of each step passes natively as the direct input argument to the next step.

Edge Cases (Crucial)

  • Empty Array: If 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).
  • Single Step: If exactly one function is provided, the returned function should behave identically to that single transformation.

Example Usage

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

Constraints

  • Must execute right-to-left
  • Must return a function
  • Must support empty array as identity
  • Must support any unary function list
Accepted19/24|Acceptance Rate79.2%