JavaScript and TypeScript course ยท Module 12: Functional Programming
Function Composition: compose and pipe
In this lesson5
A species name arrives from a sensor as ' rex ' and has to go through three treatments before it reaches the register. The expression addPrefix(capitalize(normalize(name))) reads from the inside out, and with five stages the parentheses start to look like a tangled strand of DNA. We want to write the stages in the order in which they actually run.
In the genetic laboratory of Jurassic Park, dinosaur DNA goes through a series of processing stages - extraction, purification, sequencing, validation. Each stage is a separate operation, and chaining them together produces the complete process. This is exactly how function composition works - combining simple functions into more complex operations.
What is Function Composition?
Function composition involves combining two or more functions where the output of one becomes the input of the next. Mathematically: f(g(x)) - first we apply g, then f.
Here are three workstations for treating a name: trim removes spaces from both ends, charAt(0).toUpperCase() capitalizes the first letter, and slice(1) appends the rest of the text:
// Individual operations on dinosaur data
const normalize = (name) => name.trim().toLowerCase();
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
const addPrefix = (name) => 'DINO-' + name;Each function is pure and does one thing. Now let's combine them in two ways, first by nesting the calls, then by wrapping them in a named function:
// Without composition - nested calls (hard to read)
const result = addPrefix(capitalize(normalize(' rex ')));
// 'DINO-Rex'
// With composition - readable pipeline
const formatDinoName = (name) => addPrefix(capitalize(normalize(name)));
formatDinoName(' rex '); // 'DINO-Rex'Both give 'DINO-Rex'. The second version gives the process a name and can be used over and over, but you still read the order of the stages from right to left. The compose and pipe functions automate this kind of combining for any number of stages.
The compose Function
compose chains functions from right to left - the last function in the list is executed first. This mirrors the mathematical notation f(g(x)).
The rest parameter ...fns gathers all the functions passed in into an array. reduceRight works like reduce, but walks the array from the end, and the initial value of the accumulator is the input data:
function compose(...fns) {
return (value) => fns.reduceRight(
(acc, fn) => fn(acc),
value
);
}compose itself does not process anything yet, it only returns a new function waiting for data. Let's try it on three stages of sample processing:
// Functions processing a DNA sample
const extractDNA = (sample) => ({ ...sample, dna: sample.tissue + '-DNA' });
const sequenceDNA = (sample) => ({ ...sample, sequence: sample.dna + '-SEQ' });
const validateDNA = (sample) => ({ ...sample, valid: sample.sequence.length > 5 });
// Compose: right to left (extractDNA -> sequenceDNA -> validateDNA)
const processSample = compose(validateDNA, sequenceDNA, extractDNA);
const result = processSample({ tissue: 'TREX-001' });
// { tissue: 'TREX-001', dna: 'TREX-001-DNA', sequence: 'TREX-001-DNA-SEQ', valid: true }extractDNA runs first, because it stands furthest to the right. Each stage returns a new object through spread, so the input sample { tissue: 'TREX-001' } stays untouched, and the result collects the fields added along the way.
The pipe Function
pipe is the inverse of compose - it chains functions from left to right. It reads like a natural data flow, which many programmers find more intuitive.
The implementation differs by one word, reduce instead of reduceRight, and the first function in the list runs first:
function pipe(...fns) {
return (value) => fns.reduce(
(acc, fn) => fn(acc),
value
);
}
// Pipe: left to right (natural reading direction)
const processSample = pipe(extractDNA, sequenceDNA, validateDNA);
// Identical result, but more readable orderThe same three stages give the same result as with compose, but now the order of the arguments matches the order of execution. Stages can also be functions written in place, as in this report of active dinosaurs:
// Practical example - processing park data
const processReport = pipe(
(data) => data.filter((d) => d.status === 'active'),
(data) => data.map((d) => ({ name: d.name, zone: d.zone })),
(data) => data.sort((a, b) => a.name.localeCompare(b.name)),
);
const parkData = [
{ name: 'Rex', zone: 'A', status: 'active' },
{ name: 'Stego', zone: 'B', status: 'inactive' },
{ name: 'Blue', zone: 'A', status: 'active' },
];
processReport(parkData);
// [{ name: 'Blue', zone: 'A' }, { name: 'Rex', zone: 'A' }]Stego drops out at the filter, map keeps the name and the zone, and sort with localeCompare puts the result in alphabetical order. Watch out for a trap: sort changes the array you call it on. Here it is safe, because we sort a fresh array from map, and parkData keeps its original order. If sorting were the first stage, use toSorted (ES2023), which returns a sorted copy.
Compose vs Pipe - When to Use Which?
Both functions do the same thing, but in reverse order. The choice depends on preference, which is easiest to see in a sketch with three stages:
// compose: right to left (like in mathematics)
const process1 = compose(validate, transform, parse);
// Read as: validate(transform(parse(x)))
// pipe: left to right (like a natural flow)
const process2 = pipe(parse, transform, validate);
// Read as: x -> parse -> transform -> validateIn practice, pipe is used more often because it mirrors the natural direction of data processing - from input to output, from top to bottom.
How to Build a Pipeline
A proven order of work looks like this: first define a pure function for each step, then test each one separately, next combine them with pipe or compose, and finally pass the input data to the pipeline. Stick to one rule: each stage takes one argument and returns what the next one expects. If one of them forgets its return, the next one receives undefined.
When you want to peek at the data between stages, insert a helper function called tap. It performs a side effect but passes on exactly the same value:
// Peeking at data between stages, without changing the result
const tap = (fn) => (value) => {
fn(value);
return value;
};
const debugReport = pipe(
(data) => data.filter((d) => d.status === 'active'),
tap((data) => console.log('After filter:', data.length)),
(data) => data.map((d) => d.name),
);
debugReport(parkData); // ['Rex', 'Blue'], console shows: After filter: 2The console shows the number of active dinosaurs, and the final result is still a plain list of their names - tap did not change anything in it. I recommend keeping tap at hand while debugging and removing it before deployment. In the next lesson you will see how currying turns multi-argument functions into single-argument ones that fit pipe perfectly.
Remember: pipe is a conveyor belt in the laboratory - the sample rides in from the left, passes through the workstations one after another and rides out on the right as a finished result.
Code for this lesson: index.js
// Function composition: compose and pipe
console.log("=== Jurassic Park - DNA Recombination ===\n");
// compose implementation (right -> left)
function compose(...fns) {
return (value) => fns.reduceRight((acc, fn) => fn(acc), value);
}
// pipe implementation (left -> right)
function pipe(...fns) {
return (value) => fns.reduce((acc, fn) => fn(acc), value);
}
// --- EXAMPLE 1: Formatting names ---
console.log("--- Compose: Formatting names ---");
const normalize = (str) => str.trim().toLowerCase();
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
const addPrefix = (str) => "DINO-" + str;
const formatName = compose(addPrefix, capitalize, normalize);
console.log(formatName(" rex ")); // DINO-Rex
console.log(formatName(" VELOCIRAPTOR ")); // DINO-Velociraptor
// --- EXAMPLE 2: A DNA processing pipeline ---
console.log("\n--- Pipe: Processing a DNA sample ---");
const extractDNA = (sample) => ({ ...sample, dna: sample.tissue + "-DNA" });
const sequenceDNA = (sample) => ({ ...sample, sequence: sample.dna + "-SEQ" });
const assessQuality = (sample) => ({
...sample,
quality: sample.sequence.length > 15 ? "HIGH" : "LOW",
});
const createReport = (sample) => ({
...sample,
report: sample.quality + " quality sample from " + sample.tissue,
});
const processSample = pipe(extractDNA, sequenceDNA, assessQuality, createReport);
const result = processSample({ tissue: "TREX-001" });
console.log("Result:", JSON.stringify(result, null, 2));
// --- EXAMPLE 3: Processing park data ---
console.log("\n--- Pipe: Security report ---");
const parkData = [
{ name: "Rex", zone: "A", status: "active", danger: 9 },
{ name: "Brachio", zone: "B", status: "active", danger: 2 },
{ name: "Raptor", zone: "A", status: "escaped", danger: 8 },
{ name: "Stego", zone: "B", status: "active", danger: 3 },
{ name: "Blue", zone: "A", status: "active", danger: 7 },
];
const generateReport = pipe(
(data) => data.filter((d) => d.status === "active"),
(data) => data.filter((d) => d.danger >= 5),
(data) => data.map((d) => ({ name: d.name, zone: d.zone, level: d.danger > 7 ? "CRITICAL" : "HIGH" })),
(data) => [...data].sort((a, b) => a.name.localeCompare(b.name)),
);
const report = generateReport(parkData);
console.log("Active threats:");
report.forEach((r) => console.log(` [${r.level}] ${r.name} - Zone ${r.zone}`));
// --- EXAMPLE 4: Compose vs Pipe ---
console.log("\n--- Comparing compose vs pipe ---");
const double = (x) => x * 2;
const addTen = (x) => x + 10;
const square = (x) => x * x;
const withCompose = compose(square, addTen, double);
const withPipe = pipe(double, addTen, square);
console.log("compose(square, addTen, double)(3):", withCompose(3));
console.log("pipe(double, addTen, square)(3):", withPipe(3));
console.log("Both: 3 -> double(6) -> addTen(16) -> square(256)");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. In what order does pipe execute functions?
2. What is the difference between compose and pipe?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Write normalizing and classifying functions, then combine them using pipe.
- Horizontal ordering
Arrange the elements of the pipe function implementation:
- Code editor
Group the data by zone, calculate statistics per sensor type, and count alerts.