Composition: pipe and compose
To compose functions is to feed the result of one into the next, so that a value walks through a list of steps and comes out the other side. pipe applies the steps from left to right and compose from right to left, and both are ten lines of code once reduce and functions as values are in place.
Composition is where higher-order code starts to pay off. Each step stays small and testable on its own, the order is a list that can be read and changed, and the same steps can serve two pipelines with one of them left out. This lesson writes the two helpers, shows why the order matters, and builds a pipeline from an options object.
pipe: left to right
pipe takes any number of functions and returns one function. When that function is called, the value goes through the steps in the order they were written, which is the order a reader expects. With no steps at all it returns the value unchanged, and with one it is that step.
function pipe(...functions) {
return (value) => functions.reduce((current, fn) => fn(current), value);
}
const trim = (text) => text.trim();
const lower = (text) => text.toLowerCase();
const dashes = (text) => text.replace(/\s+/g, '-');
const slug = pipe(trim, lower, dashes);
console.log(slug(' Hello World '));
console.log('no functions:', pipe()('unchanged'));
console.log('one function:', pipe(trim)(' x '));
node pipe.js
hello-world
no functions: unchanged
one function: x
The reduce carries the value from step to step: the accumulator starts as the input and each function replaces it with its own result. That is why the empty pipeline returns the value and why a pipeline of one step needs no special case. The three steps are pure functions of a string, which is the point: each can be tested with one call, and the pipeline is the only place where they are known to belong together.
compose: right to left
compose is the same idea in the order mathematics writes it: the last function is the innermost, so the call reads compose(dashes, lower, trim)(value) and the value meets trim first. The implementation is a reduceRight, and the result is the same text as the pipe.
function compose(...functions) {
return (value) => functions.reduceRight((current, fn) => fn(current), value);
}
function pipe(...functions) {
return (value) => functions.reduce((current, fn) => fn(current), value);
}
const trim = (text) => text.trim();
const lower = (text) => text.toLowerCase();
const dashes = (text) => text.replace(/\s+/g, '-');
const slug = compose(dashes, lower, trim);
console.log('compose:', slug(' Hello World '));
console.log('pipe:', pipe(trim, lower, dashes)(' Hello World '));
console.log('the same text:', slug(' X ') === pipe(trim, lower, dashes)(' X '));
node compose.js
compose: hello-world
pipe: hello-world
the same text: true
Two helpers, one result, and the difference is only the order of the arguments at the place where the pipeline is built. The last line compares two calls on a third input, so the equality is not a coincidence of one string. A project picks one of the two and uses it everywhere; mixing them makes every pipeline a small puzzle about which end runs first.
The order matters
The steps of the slug example would give the same answer in any order, which is a trap: most pipelines are not that forgiving. The program below pairs a step that appends a letter with a step that cuts the text to three characters, and the two orders give different strings.
const append = (text) => text + 'a';
const firstThree = (text) => text.slice(0, 3);
function pipe(...functions) {
return (value) => functions.reduce((current, fn) => fn(current), value);
}
console.log('append then cut:', pipe(append, firstThree)('abc'));
console.log('cut then append:', pipe(firstThree, append)('abc'));
const steps = [
(value) => value + 1,
(value) => value * 2,
(value) => value - 3,
];
console.log('reduced:', steps.reduce((value, fn) => fn(value), 4));
let trace = 4;
for (const fn of steps) {
trace = fn(trace);
console.log('a step leaves', trace);
}
node order.js
append then cut: abc
cut then append: abca
reduced: 7
a step leaves 5
a step leaves 10
a step leaves 7
Appending first and cutting after loses the appended letter, so the first pipeline looks like it did nothing at all. The last three lines are the same pipeline with a console.log after every step: 4 becomes 5, 5 becomes 10, and 10 becomes 7. That is the debugging technique a pipeline asks for, because a single step is easy to check and the sequence is where the surprise lives.
A pipeline built at run time
Once a pipeline is an array of functions, it can be built by code: steps can be added conditionally from an options object, and the caller decides which ones it wants. The program below builds a text pipeline from two switches, which is the shape of a formatter, a query builder or an exporter.
function pipe(...functions) {
return (value) => functions.reduce((current, fn) => fn(current), value);
}
const trim = (text) => text.trim();
const upper = (text) => text.toUpperCase();
const dashes = (text) => text.replace(/\s+/g, '-');
function buildPipeline({ loud = false, slug = false } = {}) {
const steps = [trim];
if (loud) {
steps.push(upper);
}
if (slug) {
steps.push(dashes);
}
return pipe(...steps);
}
console.log(buildPipeline()(' a b '));
console.log(buildPipeline({ loud: true })(' a b '));
console.log(buildPipeline({ slug: true })(' a b '));
console.log(buildPipeline({ loud: true, slug: true })(' a b '));
console.log('trim only:', buildPipeline()(' keep me '));
node arrays.js
a b
A B
a-b
A-B
trim only: keep me
One builder, four pipelines, and every line of the output can be predicted from the two switches. The options object is the one from lesson 037, the spread of the array into pipe is the one from lesson 022, and the steps are pure functions from lesson 038. This is the point of the whole part: small functions, combined by code that is itself ordinary JavaScript.
Exercises
- Add a step to slug in pipe.js that removes a trailing dash. Where in the list does it have to stand, and why?
- Call compose(trim, lower) with an upper-case word and then call pipe(trim, lower) with the same word. Are the two results the same?
- Write compose in terms of pipe instead of reduceRight. Which list has to be passed in the other direction, and what does that do to the rest array of the function?
- Remove the trim step from the first pipeline in order.js and run the file again. Which of the two lines changes?
- Add an option exclaim to buildPipeline in arrays.js that appends a !, and decide where it belongs in the list. What does the output become for all four switches on?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
pipe(f, g, h)return?Answer
A function that calls f, then g, then h on the result
pipe returns a new function and the steps run when it is called with a value.
-
How does
composediffer frompipe?Answer
It runs the functions from right to left
compose follows the mathematical order, so the last argument is the first function to see the value.
-
What does this program print?
const pipe = (f, g) => (x) => g(f(x)); console.log(pipe((n) => n + 1, (n) => n * 2)(3));Answer
8
Three becomes four in the first step and eight in the second.
-
What does this program print?
const compose = (f, g) => (x) => f(g(x)); console.log(compose((n) => n + 1, (n) => n * 2)(3));Answer
7
The rightmost function runs first, so three becomes six and then seven.
-
What is the accumulator of the reduce inside
pipe?Answer
The value being passed from step to step
It starts as the input of the pipeline and each function replaces it with its result.
-
What does this program print?
function pipe(...fns) { return (v) => fns.reduce((c, f) => f(c), v); } console.log(pipe()(5));Answer
5
With no steps the reduce has nothing to do and returns the value it started with.
-
What does this program print?
const pipe = (...fns) => (v) => fns.reduce((c, f) => f(c), v); const cut = (t) => t.slice(0, 2); const add = (t) => t + "x"; console.log(pipe(cut, add)("abc"), pipe(add, cut)("abc"));Answer
abx ab
Cutting first leaves two characters and the appended letter survives; appending first leaves three characters and the cut removes it.
-
Why is a pipeline easy to test?
Answer
Each step is a small function that can be called on its own
A step is tested with one input and one expected output, and the pipeline is tested once for the order.
-
How is a pipeline built from an options object?
Answer
Steps are pushed into an array conditionally and spread into pipe
An array of functions can be built with if statements and then handed to pipe with the spread syntax.
-
What goes wrong when the steps of a pipeline are in the wrong order?
Answer
Each step still runs, but on a value the next one did not expect
A pipeline does not check the types of its steps, so a wrong order gives a wrong value rather than an error.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev