Replace Loop with Pipeline

Removes smells
Compare
Symptom
Human

Imperative for/while loops where filter, map, and reduce concerns are mixed by hand — the reader must mentally execute the body to learn what's being produced.

Agent

Imperative for/while loops where the agent must mentally execute the body to learn the result; the loop's purpose isn't readable from its shape.

Goal
Human

Filter / map / reduce expresses the transformation as a sequence of named operations; intent reads in domain language.

Agent

Transformations read as named operation sequences (filter, map, reduce); the agent recognizes the shape without simulating the loop.

Before the refactoring

const seniors = [];
for (const u of users) {
if (u.age >= 65) seniors.push(u.name);
}

After the refactoring

const seniors = users
.filter(u => u.age >= 65)
.map(u => u.name);
Example source: Illustrative example written for this site, not a quotation from any source.
Pressure
Human

Off-by-one errors and accumulator bugs hide in the body and only surface at test time; intent is buried under the mechanism.

Agent

The agent must trace the loop body step by step to verify behavior; off-by-one bugs hide where the agent's mental simulation diverges from runtime.

Tradeoff
Human

Pipelines add a tiny per-element function-call overhead — usually negligible, but profile if the call is on a hot path.

Agent

Pipeline form adds per-element call overhead and forces the agent to track intermediate collection types through the chain; for hot paths the runtime cost matters.

Relief
Human

Off-by-one and accumulator bugs vanish; each step is independently testable.

Agent

Each pipeline stage carries a typed input and output; the agent verifies one stage against its signature instead of simulating accumulator state across the loop's iterations to predict the result.

Trap
Human

Forcing every loop into a pipeline — including ones with early-exit, side-effect accumulators, or genuinely sequential dependencies — produces .reduce() bodies harder to read than the original.

Agent

Forcing every loop into a pipeline, including ones with early-exit, side-effects, or sequential dependencies, produces .reduce() bodies whose accumulator state the agent has to simulate at every read; the simulation cost exceeds what the original loop's straight-line control flow required.