Sub topic 9
Composing Functions with pipe and compose
This chapter assumes you know arrow functions, rest parameters (...fns), and how reduce folds an array into one value. It also assumes you have read the earlier chapters on pure functions and higher-order functions.
The idea: small functions, one pipeline
Function composition means building a new function by feeding the output of one function into the next. Without a helper, you nest the calls:
const trim = (s) => s.trim();
const toUpper = (s) => s.toUpperCase();
const exclaim = (s) => `${s}!`;
console.log(exclaim(toUpper(trim(' hi ')))); // HI!This works, but you have to read it from the inside out, and each new step adds another layer of parentheses. Composition helpers let you write the steps as a flat list.
Building pipe and compose
pipe runs functions from left to right. compose runs them from right to left, which matches how mathematical notation writes f(g(x)). Each helper is one line of reduce:
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}!`;
const shout = pipe(trim, toUpper, exclaim);
const shout2 = compose(exclaim, toUpper, trim);
console.log(shout(' hi ')); // HI!
console.log(shout2(' hi ')); // HI!Both helpers return a function and run nothing until you call it. The starting value x is the accumulator, and each function turns the current value into the next one.
Why it works best with pure functions
Composition relies on each step depending only on its input. When every function is pure, you can test each step on its own, reorder or remove steps safely, and reuse the same pipeline anywhere. A step that reads or changes outside state makes the pipeline's result depend on when it runs, so you lose those guarantees.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Mixing up the order | `compose(trim, toUpper, exclaim)` runs `exclaim` first | Use `pipe` when you want to read left to right |
| Steps that need more than one argument | The extra parameters arrive as `undefined` | Wrap the step: `(s) => s.padStart(5, '*')` |
| A step returns nothing | Every later step receives `undefined` | Make sure each step returns a value |
| Async steps | Later steps receive a Promise | Use an async pipe, shown below |
The helpers above pass only one argument from step to step, so every step must be unary, meaning it takes exactly one argument. The next chapter on currying shows a systematic way to turn multi-argument functions into unary ones.
If any step returns a Promise, chain the steps on a resolved Promise:
const pipeAsync = (...fns) => (x) =>
fns.reduce((p, fn) => p.then(fn), Promise.resolve(x));
const fetchName = async (id) => `user${id}`;
pipeAsync(fetchName, (s) => s.toUpperCase())(7).then(console.log); // USER7Exercise
Using pipe, build a slugify function that trims a string, lowercases it, and replaces each run of whitespace with a single hyphen, so slugify(' Hello Functional World ') returns 'hello-functional-world'.
Show answer
const slugify = pipe((s) => s.trim(), (s) => s.toLowerCase(), (s) => s.replace(/\s+/g, '-')); Each step is unary and pure. Trimming first stops leading and trailing spaces from becoming hyphens.
Exercise
What does compose((n) => n + 1, (n) => n * 2)(5) return, and what does pipe with the same arguments return?
Show answer
compose applies the rightmost function first, so it returns (5 2) + 1 = 11. pipe applies the leftmost function first, so it returns (5 + 1) 2 = 12.