Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Implement pipe()

A Closer Look at Functionshard

Implement `pipe(...fns)` that returns a function composing the given functions left to right: the output of each becomes the input of the next. `pipe(f, g, h)(x)` should compute `h(g(f(x)))`. With no functions, the result is the identity function.

Examples

Input: const f = pipe((x) => x + 1, (x) => x * 2, (x) => x - 3); f(5)
Output: 9
((5 + 1) * 2) - 3 = 9.
Input: pipe()(42)
Output: 42
An empty pipe returns its input unchanged.

Sample tests

Input: left-to-right composition
Output: 9
Input: single function
Output: 70

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Composing right-to-left gives `compose`, not `pipe` — order matters.
  • Forgetting that an empty function list must behave as the identity (reduce with the input as the initial value handles this for free).

Learning resources

  • MDN: Array.prototype.reduce()
  • MDN: Functions guide
Approach & explanation (try first)

`pipe` is a left fold over the functions, using the input as the seed of the reduction. Each function transforms the running value. Because the seed is the input itself, an empty pipe naturally returns the input unchanged.

Loading...
⌘/Ctrl + Enter

Run your code to see results.