coding round · ~10 min
JavaScriptbeginner

Implement compose and pipe

Write two helpers for function composition:

  • pipe(...fns) returns a function that runs fns left to right, passing each result to the next function
  • compose(...fns) does the same right to left, so compose(f, g)(x) is f(g(x))

The first function to run may receive any number of arguments; every later one receives the single previous result. With no functions, both return a function that gives back its first argument unchanged.

  • pipe((x) => x + 1, (x) => x * 2)(3) → 8
  • compose((x) => x + 1, (x) => x * 2)(3) → 7
  • pipe((a, b) => a + b, (x) => x * 10)(2, 3) → 50
  • compose()(5) → 5

Define compose, pipe in the editor. 7 tests will call them.

solution.js
function pipe(...fns) {
  // Return a function that runs fns from left to right.
}

function compose(...fns) {
  // Return a function that runs fns from right to left.
}

Tests⌘/Ctrl + Enter to run

pipe runs functions left to right
compose runs functions right to left
chains many functions
the first function to run receives all the arguments
returns the input unchanged when given no functions
works with a single function
returns a reusable function and calls nothing up front
esc