The sensors in Mr. Tono's paddy plots keep sending moisture numbers, broken sensors included. Mr. Tono doesn't need the raw numbers. He only wants to know which plots need water. Between the raw numbers and that answer, the data has to be cleaned, marked and then counted, one step at a time.
This chain of steps is called a data pipeline: stages that data passes through one after another. The output (the result) of one stage becomes the input of the next. It works like Mr. Tono's bamboo gutters from the spring to the paddy: water only flows when each gutter's mouth meets the mouth of the next one. In a pipeline, each gutter is one stage, and the water is the data. Mouths that meet mean that the shape of the data one stage puts out fits what the next stage takes in.
A stage: one function, one job
A stage is one function: it takes data, then returns data. The data in this example is the readings from the sensors in the paddy plots, arriving over a WebSocket every few seconds. Each reading is one object with the plot's name and its moisture number:
const readings = [
{ plot: 'A', moisture: 18 },
{ plot: 'B', moisture: null }, // its sensor is broken
{ plot: 'C', moisture: 42 },
{ plot: 'D', moisture: 9 },
];
The question: how many plots are dry (moisture below 20)? Rather than one big function that does everything, split it into three small stages: drop the broken readings, mark the dry ones, count the dry ones. Each stage has a single job, so it is easy to read and easy to test on its own.
map, filter and reduce as a flow
These three array methods make good stages, because each takes a list and it is clear what each puts out. This code chains all three: the result of each method goes straight into the method on the next line.
const dryCount = readings
.filter((b) => b.moisture !== null)
.map((b) => ({ ...b, dry: b.moisture < 20 }))
.reduce((n, b) => (b.dry ? n + 1 : n), 0);
console.log(dryCount); // 2
{ ...b, dry: ... }makes a new object: a copy of the readingb, plus adryfield.reducestarts from0(written at the end of the.reduceline), then adds 1 for each reading that isdry.
Look at the shape of the data at each gutter mouth, that is, after each stage:
| After the stage | Shape of the data | What it holds |
|---|---|---|
| (start) | a list of 4 readings | A, B, C, D |
filter |
a list of 3 readings | A, C, D: B is dropped |
map |
a list of 3 readings | the same, each reading now has dry |
reduce |
one number | 2 (A and D) |
filtersieves: each item stays in or is dropped, so the count can go down.mapchanges every item: the count stays the same, the contents change.reducegathers every item into one value. After it there is no list any more, soreduceusually sits at the end, like the paddy at the end of the gutters.
These three array methods are covered in the JavaScript lessons. Here the focus is how to chain them into a flow.
Chaining stages with pipe
Each stage can also be kept as an ordinary function with its own name, then chained with pipe. pipe (line 1 of the code below) takes the stages and returns one new function that runs the data through all of them, from left to right.
const pipe = (...stages) => (data) => stages.reduce((result, t) => t(result), data);
const dropBroken = (list) => list.filter((b) => b.moisture !== null);
const markDry = (list) => list.map((b) => ({ ...b, dry: b.moisture < 20 }));
const countDry = (list) => list.filter((b) => b.dry).length;
const report = pipe(dropBroken, markDry, countDry);
console.log(report(readings)); // 2
pipe(dropBroken, markDry, countDry)doesn't run anything yet.pipeonly connects the gutters, and its result,report, is a function ready to be called.- When
report(readings)is called,readingsgoes intodropBroken. Its result goes intomarkDry, then the result ofmarkDrygoes intocountDry. - Inside
pipe,...stagescollects all the stages into one array. Thenreducecarries the result so far from one stage to the next, starting fromdata. - To add a stage, for example rounding the sensor values, put one more function into the
pipe(...)list. The other stages stay as they are.
The rule is the same as with gutters: each stage has to accept the shape of the data the stage before it puts out. countDry needs a list of readings that already have dry, so this function has to come after markDry.
Branching: sending items down several channels
Sometimes different items need different paths. Dry plots get a warning, plots that are wet enough are only logged. Like a T-shaped gutter that splits the water two ways, you split the flow by a condition. The function branch below puts each item into one channel. Its result is the object channels: each key is a channel name, and its value is the list of items for that channel.
function branch(list, pickChannel) {
const channels = {};
for (const item of list) {
const name = pickChannel(item);
if (!channels[name]) channels[name] = [];
channels[name].push(item);
}
return channels;
}
const result = branch(dropBroken(readings), (b) => (b.moisture < 20 ? 'dry' : 'moist'));
console.log(Object.keys(result)); // [ 'dry', 'moist' ]
console.log(result.dry.map((b) => b.plot)); // [ 'A', 'D' ]
pickChannelis a function you give tobranch. For each item, it answers one question: which channel does this item go into? Here the answer is'dry'or'moist'.- Each channel can then have a pipeline of its own:
result.drygoes through a send-a-warning stage,result.moistthrough a save stage. - If they need joining again later, merge the lists:
[...result.dry, ...result.moist].
In this example pickChannel always returns a name, so no item gets lost on the way. Compare that with two separate ifs, one for < 20 and one for > 30. A reading of 25 matches neither and is lost without anyone noticing, just like water that spills from a gutter mouth that isn't connected to anything.
The order of stages matters
Calculate it first. You have 1,000 readings from the paddy's moisture sensors, and 900 of them are broken (their value is null). You need to drop the broken ones with filter and transform the rest with map. If you transform first and drop afterwards, how many times is the function inside map called? And if you drop first?
If you transform first, map is called for 1,000 readings, including the 900 that get dropped right after. If you drop first, map is called only 100 times. Both orders give the same end result, but dropping first is ten times less work. A practical rule: filter as early as you can.
The order can also change the result, not just the speed. Say all holds the readings from plots A to E, and the sensor in B is broken. You want the first three readings whose sensor works. slice(0, 3) takes the first three items:
all.slice(0, 3).filter((b) => b.moisture !== null); // A, C: only two
all.filter((b) => b.moisture !== null).slice(0, 3); // A, C, D
The first line takes three first (A, B, C), then drops B, so two are left. The second line drops first, then takes three. Before swapping two stages, ask: does the second stage depend on what the first one dropped or changed?
💡 Backpressure: when a stage downstream is too slow
A stage downstream is a later stage, closer to the end of the flow. Upstream is the direction of the data's source. Imagine orders coming in over a WebSocket at 10 a second, while the stage that saves them to the database needs 250 ms (milliseconds) per order. So that stage manages only 4 a second. Every second 6 more orders pile up in front of it, and a minute later 360 orders are waiting. You have three choices:
- Hold them in a buffer (a temporary waiting area) with a size limit. Good for a short burst.
- Drop some, for example keep only the latest reading. Good for data that may be lost, such as a cursor position or a sensor that sends again every second anyway.
- Or ask upstream to slow down: the slow stage tells its source to wait until that stage is ready.
That last choice is what backpressure means. You need it whenever all the data has to arrive, as orders do. Node.js streams (flows of data) do it this way: write() returns false when the destination is full, so the sender stops for a while. Then a drain event comes when the destination can take more.
⚠️ Gutters that leak or don't connect
- A stage that forgets
return.(list) => { list.map(...) }uses curly braces but noreturn, so it gives backundefined. The next stage stops with the errorCannot read properties of undefined. The gutter mouths don't meet. - A
mapthat changes the original item.b.dry = trueinsidemapchangesreadingstoo, so other channels see data that has already changed. Make a new object instead:{ ...b, dry: true }. - A branch with no channel for every item. An item that matches none of the conditions disappears without anyone noticing. Make sure every item has somewhere to go, with an
otherchannel if needed. - A
reducein the middle of the pipeline. Afterreduceyou hold one value, not a list, so afilterormapafter it fails.
TL;DR: A data pipeline is a chain of small stages, and each stage is one function with one job. Each stage's output is the next stage's input, so the shapes of the data (a list, or one value) have to fit. filter drops the items that don't meet a condition, map changes every item, and reduce gathers every item into one value, usually at the end. pipe(a, b, c) chains stages from left to right: the data goes into a first, then b, then c. To branch, pick exactly one channel (path) for each item so nothing gets lost. Filter as early as you can, and remember that the order of stages can change the result. When a stage downstream (a later stage) is too slow: hold, drop, or ask upstream (the data's source) to slow down. That last choice is called backpressure.
⚡ Stage after stage
Write:
const dryCount = readings
.filter((b) => b.moisture !== null)
.map((b) => ({ ...b, dry: b.moisture < 20 }))
.reduce((n, b) => (b.dry ? n + 1 : n), 0);
console.log(dryCount); // 2
Meaning: readings is a list of moisture readings from the sensors in the paddy plots, and a broken sensor's reading is null. This code counts the dry plots (moisture below 20). Each method is one stage, and the output of each stage goes straight in as the input of the next. filter drops the broken readings, so the number of items can go down. map changes every item (here it adds a dry field), and the count stays the same. reduce gathers every item into one value, not a list, so it usually sits at the end.
⚡ Chaining with pipe
Write:
const pipe = (...stages) => (data) => stages.reduce((result, t) => t(result), data);
const dropBroken = (list) => list.filter((b) => b.moisture !== null);
const markDry = (list) => list.map((b) => ({ ...b, dry: b.moisture < 20 }));
const countDry = (list) => list.filter((b) => b.dry).length;
const report = pipe(dropBroken, markDry, countDry);
console.log(report(readings)); // 2
Meaning: pipe doesn't run anything yet: it only chains three stages into one new function, report. When report(readings) is called, the data flows from left to right: dropBroken, then markDry, then countDry. Each stage has to accept the shape of the data the stage before it puts out. For example, countDry needs readings that already have dry, so it comes after markDry.
⚡ Filter as early as you can
Guess first: 1,000 readings, 900 of them broken. If you transform first with map and drop afterwards with filter, how many times is map called?
1,000 times, including the 900 that get dropped right after. Drop first, and it's only 100.
Meaning: Both orders give the same end result, but dropping first is ten times less work. In other cases the order can change the result, so before swapping two stages, check whether the second depends on what the first one dropped or changed.