Sub topic 9
Composing Functions with pipe and compose
Function composition means building a new function by feeding the output of one function into the next. If f turns an A into a B and g turns a B into a C, composing them gives a function that turns an A straight into a C. In JavaScript you can write this as nested calls, g(f(x)). Nesting gets hard to read after two or three levels, so functional code usually relies on two small helpers, pipe and compose.
This chapter assumes you are comfortable with arrow functions, rest parameters (...fns), higher-order functions, and Array.prototype.reduce. It also assumes you know what makes a function pure. Composition works best when every step is pure.
From nesting to pipelines
Here is a string clean-up written as nested calls:
const trim = (s) => s.trim();
const toUpper = (s) => s.toUpperCase();
const exclaim = (s) => `${s}!`;
console.log(exclaim(toUpper(trim(' hi ')))); // HI!You have to read the nested version from the inside out: trim runs first, even though exclaim is written first. The more steps you add, the harder it is to see the order. Composition helpers let you name the pipeline once and reuse it.
Implementing pipe and compose
Both helpers take any number of functions and return a new function of one argument. pipe applies the functions left to right. compose applies them right to left, which matches the order of mathematical notation (g ∘ f)(x) = g(f(x)).
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const trim = (s) => s.trim();
const toUpper = (s) => s.toUpperCase();
const exclaim = (s) => `${s}!`;
console.log(pipe(trim, toUpper, exclaim)(' hi ')); // HI!
console.log(compose(exclaim, toUpper, trim)(' hi ')); // HI!Here is how pipe works internally. reduce starts with the input x as the accumulator. At each step it calls the current function on the accumulator and passes the result forward. When the list runs out, the accumulator holds the final output. compose does the same thing with reduceRight, so it starts from the last function.
Choosing between them
| Helper | Reading order | Matches | Common in |
|---|---|---|---|
| `pipe` | Left to right, in execution order | Unix shell pipes, method chains | Application code, Ramda's `pipe`, lodash's `flow` |
| `compose` | Right to left, in nesting order | Math notation `g(f(x))` | Haskell-influenced code, Redux's `compose` |
Both helpers produce the same result. Pick one per codebase and use it consistently. Most JavaScript teams prefer pipe because the code reads in the order it runs.
A realistic pipeline
Composition pays off when each step is small, named, and reusable. This slug generator turns titles into URL fragments:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const stripPunctuation = (s) => s.replace(/[^a-z0-9\s-]/g, '');
const words = (s) => s.split(/\s+/);
const joinWithDash = (parts) => parts.join('-');
const slugify = pipe(trim, lower, stripPunctuation, words, joinWithDash);
console.log(slugify(' Hello, World of FP ')); // hello-world-of-fp
console.log(slugify('Composing Functions!')); // composing-functionsNotice that the types change along the way. words turns a string into an array, and joinWithDash turns the array back into a string. Composition only requires each step's output to fit the next step's input.
Array transformations compose the same way. You can wrap each stage of a filter/map/reduce chain in a named function and recombine the stages however you need:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const paidOnly = (orders) => orders.filter((o) => o.paid);
const totals = (orders) => orders.map((o) => o.total);
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const revenue = pipe(paidOnly, totals, sum);
const orderCount = pipe(paidOnly, (xs) => xs.length);
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 60, paid: true }
];
console.log(revenue(orders)); // 100
console.log(orderCount(orders)); // 2Method chaining only works with methods that already exist on the object. Composition works with any function, so you can reuse paidOnly in pipelines that Array.prototype knows nothing about.
Properties worth knowing
Composition is associative. You can group steps however you like and the result does not change. This lets you build small pipelines and nest them inside bigger ones.
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const inc = (n) => n + 1;
const double = (n) => n * 2;
const square = (n) => n * n;
console.log(pipe(inc, pipe(double, square))(3)); // 64
console.log(pipe(pipe(inc, double), square)(3)); // 64
console.log(pipe(inc, double, square)(3)); // 64An empty pipeline is the identity function. pipe() returns its input unchanged, because reduce with an initial value and no elements returns the initial value. This matters when you build a pipeline from a list that might be empty, such as a list of optional middleware.
Common errors
Steps that take more than one argument
Every step after the first receives exactly one value. A step like s.split(sep) needs a separator too. To fit it into a pipeline, fix the extra argument ahead of time with a wrapper:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const split = (sep) => (s) => s.split(sep);
const join = (sep) => (parts) => parts.join(sep);
const csvToPipes = pipe(split(','), join(' | '));
console.log(csvToPipes('a,b,c')); // a | b | cThe next chapter, on currying, turns this wrapper trick into a general technique.
Reversed order
If you call compose(trim, toUpper, exclaim) and expect pipe order, you get exclaim first. With strings this can still look almost right: the result here is " HI !", with the stray spaces kept. Write a test with input that makes the order visible.
Mismatched shapes
If one step returns an array and the next expects a string, the error appears deep inside the pipeline, often as x.trim is not a function. The stack trace points at the anonymous reduce callback, not the step you broke.
Impure steps
A step that mutates its input or reads global state breaks the main promise of composition: that you can understand each step on its own. If a step must perform I/O, put it at the end of the pipeline or outside it.
Debugging with tap
Because a pipeline has no intermediate variables, you cannot set a breakpoint on a named value. A tap helper runs a side effect, such as logging, and passes its input through unchanged:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const tap = (fn) => (x) => {
fn(x);
return x;
};
const process = pipe(
(s) => s.trim(),
tap((v) => console.log('after trim:', JSON.stringify(v))),
(s) => s.toUpperCase()
);
console.log(process(' hi ')); // logs: after trim: "hi" then HIRemove tap calls before you commit, or route them through a logger you can switch off.
Asynchronous pipelines
Plain pipe passes a Promise to the next step as if it were a value. That breaks as soon as one step is async. An async version chains the steps with .then:
const pipeAsync = (...fns) => (x) =>
fns.reduce((p, fn) => p.then(fn), Promise.resolve(x));
const fetchUser = async (id) => ({ id, name: 'ada' });
const capitalize = (u) => ({ ...u, name: u.name[0].toUpperCase() + u.name.slice(1) });
const greet = (u) => `Hello, ${u.name}`;
pipeAsync(fetchUser, capitalize, greet)(7).then(console.log); // Hello, AdapipeAsync accepts both sync and async steps, because .then wraps plain return values in a Promise. A rejection in any step skips the remaining steps and goes to the final .catch.
Cost and when not to compose
Every step is a function call, and each array step allocates a new array. For typical application data this cost is negligible. In hot loops over very large arrays, a single reduce or for loop that does all the work in one pass can be faster. Measure before you optimize.
Composition also hurts readability when the steps are anonymous and clever. A pipeline of five well-named functions is easy to read. A pipeline of five inline lambdas is usually worse than a short block of plain statements.
Exercise
What does pipe(n => n * 10, n => n + 1, String)(4) return, and what would compose with the same arguments in the same order return?
Show answer
pipe returns the string "41": 4 10 = 40, then 40 + 1 = 41, then String(41). compose runs right to left: String(4) is "4", then "4" + 1 is the string "41", then "41" 10 is the number 410. compose returns 410.
Exercise
Write a function countWords using pipe and small named steps. It takes a sentence and returns the number of non-empty words, so countWords(' the quick fox ') returns 3.
Show answer
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x); const trim = (s) => s.trim(); const words = (s) => s.split(/\s+/); const nonEmpty = (xs) => xs.filter((w) => w.length > 0); const length = (xs) => xs.length; const countWords = pipe(trim, words, nonEmpty, length); The nonEmpty step handles the empty string: ''.split(/\s+/) returns [''], so without it countWords('') would return 1 instead of 0.
Exercise
Why does pipe(fetchUser, greet)(7) fail when fetchUser is async, and what is the smallest change that fixes it?
Show answer
fetchUser returns a Promise, so greet receives the Promise instead of a user object, and u.name is undefined. Replace pipe with a version that chains steps with .then, such as pipeAsync = (...fns) => (x) => fns.reduce((p, fn) => p.then(fn), Promise.resolve(x)).