11. Implement compose and pipe — Function Composition

medium

compose and pipe are the heart of functional pipelines (Redux middleware, RxJS, Ramda). They're really a reduce question.

The idea

  • pipe reads in source order: reduce left-to-right, each result feeding the next function.
  • compose is the mathematical f(g(x)): same thing with reduceRight.

Follow-ups

  • "Multiple starting arguments?" → only the first function can be variadic; see the Solution tab.
  • "Async steps?" → await each: reduce((p, fn) => p.then(fn), Promise.resolve(input)).
  • "Empty input — pipe()(x)?" → reduce with the seed returns x unchanged.

What to practice

Write both, then an async pipe that awaits each step — a frequent extension.

More questions

index.js
function compose(...fns) {
  // your code here — right-to-left
}

function pipe(...fns) {
  // your code here — left-to-right
}

const inc = (x) => x + 1;
const double = (x) => x * 2;
console.log(compose(inc, double)(5)); // inc(double(5)) = 11
console.log(pipe(inc, double)(5));    // double(inc(5)) = 12

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.