Course contentsShow
← JavaScript
Lesson 481 of 2,72312. Higher-Order FunctionsFree lesson

Composing with Array Methods

Using reduce to build flexible compose and pipe functions that accept multiple arguments.

Composing with Array Methods

You'll learn how to use reduce to build flexible compose and pipe functions that accept multiple arguments.

Understanding Reduce-Based Composition

In the previous lessons, you built compose and pipe functions that worked with single-argument functions. But what if your first function needs multiple arguments? The key is using reduce cleverly to handle the initial call differently.

Building a Flexible Compose

Instead of immediately reducing through all functions, you can return a new function that accepts any number of arguments, then feeds them to the first function:

const compose = (...fns) => (...args) => 
  fns.reduceRight((acc, fn) => fn(acc), fns[0](...args));

const multiply = (a, b) => a * b;
const double = x => x * 2;
const addOne = x => x + 1;

const calculate = compose(addOne, double, multiply);
calculate(3, 4); // multiply(3, 4) → 12 → double(12) → 24 → addOne(24) → 25

Notice how fns[0](...args) spreads all arguments into the first function (actually the last in the compose order), then the result flows right-to-left through the remaining functions.

Building a Flexible Pipe

The same approach works for pipe, but the initial function is naturally first:

const pipe = (...fns) => (...args) => 
  fns.slice(1).reduce((acc, fn) => fn(acc), fns[0](...args));

const calculate = pipe(multiply, double, addOne);
calculate(3, 4); // 25 (same result, different reading order)

Here, fns[0](...args) calls the first function with all arguments, then slice(1) and reduce handle the rest of the pipeline.

Key Takeaway: By wrapping your reduce composition in a function that returns another function, you can accept multiple arguments for the initial operation while maintaining clean single-argument flow through the rest of the pipeline.