CodePark/ problems / compose and pipe
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Closures and higher-order functions

compose and pipe

mediumabout 15 minutes in an interview

Implement two functions that chain other functions into one.

  • compose(f, g, h) returns a function that runs right to left: f(g(h(...args))).
  • pipe(f, g, h) returns a function that runs left to right: h(g(f(...args))).

Rules for both:

  • The first function to run receives all the arguments. Every later one receives the previous return value.
  • With no functions, the returned function returns its first argument unchanged.
  • Nothing runs until the returned function is called. The returned function can be called many times.
Input: compose(x => x + 1, x => x * 2)(5) Output: 115 * 2 = 10 runs first, then 10 + 1.
Input: pipe(x => x + 1, x => x * 2)(5) Output: 12
Input: pipe((a, b) => a + b, n => n * 10)(2, 3) Output: 50