Javascript Fundamentals · Interview Challenges

Compose functions with pipe

pipe

Compose functions with pipe

A checkout applies tax, then a discount, then formats a label. Each step is a small function. Writing label(discount(tax(cart))) nests the calls and reads inside out — the first step is buried deepest, and a stray bracket is hard to spot.

pipe chains the functions left to right instead: the output of each becomes the input of the next. pipe(f, g, h)(x) means h(g(f(x))). It turns a nest of calls into a readable left-to-right list — the data-flow pattern.

The shape folds over the functions with reduce, threading a running value:

function pipe(...fns) {
  return (input) => fns.reduce((value, fn) => fn(value), input);
}

reduce starts with input and applies each function in turn, so the value flows left to right. A reduceRight would run them the other way — that is compose, not pipe. An empty list returns the input untouched.

Export pipe from index.js. Your job is to run the functions left to right, feeding each result into the next.

Challenge

A chain of small steps — apply tax, then discount, then label — is easy to write nested and hard to read. Export a pipe function from index.js to run them left to right.

pipe takes any number of single-argument functions and returns a new function. Calling the returned function with a value runs each function in order — the result of one feeding into the next — and returns the final result.

index.js
export function pipe(..._fns) {
  return (input) => input;
}

export function render(mount) {
  const run = pipe(
    (value) => value + 1,
    (value) => value * 2,
  );

  const line = document.createElement('p');
  line.textContent = `pipe(+1, ×2)(3) → ${run(3)}`;
  mount.replaceChildren(line);
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.