Skip to content
jshacks.dev
Functions

How to Build a Pipeline of Transformations With reduce

Build a pipeline of transformations in JavaScript with reduce, with named steps, early exit, async steps and whole collections, plus tests. Node.js 24.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Node.js, npm and Vite logos.

Data rarely arrives in the shape you need. A list of raw rows has to be trimmed, parsed, validated, converted and summarized, and the straightforward way to write it is a sequence of assignments: const a = trim(x); const b = parse(a); const c = validate(b);. That works until the sequence changes at runtime, for example when a user picks which cleanup steps to apply, or when the same steps are reused in three places. Then you want the steps as a list and a way to run them in order. Array.prototype.reduce does that in one line, and most of the interest lies in what you build around it. This post constructs a pipeline of transformations on Node.js 24: the core reduce, named steps for readable errors, steps that filter and stop, async steps and a version that runs over a whole collection. For the underlying idea in its general form, see function composition in data pipelines.

The core idea

reduce walks an array with an accumulator. If the array holds functions and the accumulator is the current value, each step applies one function to the value and passes the result on.

JavaScript
const pipeline = (...steps) => (input) => steps.reduce((value, step) => step(value), input);

const normalize = pipeline(
  (s) => s.trim(),
  (s) => s.toLowerCase(),
  (s) => s.replace(/\s+/g, " "),
);

console.log(normalize("  Hello    WORLD  "));
Text
hello world

The initial value is the input, and the callback applies the next function to the running value. The accumulator is the data flowing through, not a total, which is the part that surprises people who know reduce only as a way to sum numbers. Because the steps are an array, you can build it from configuration, filter it, reorder it and share it between pipelines.

JavaScript
const steps = {
  trim: (s) => s.trim(),
  lower: (s) => s.toLowerCase(),
  dashes: (s) => s.replaceAll(" ", "-"),
};

const selected = ["trim", "lower", "dashes"].map((name) => steps[name]);

console.log(pipeline(...selected)("  My Post Title "));
Text
my-post-title

A list of names, perhaps loaded from a file, becomes a working pipeline with one map. That is the main advantage over writing the calls out by hand.

An empty pipeline

What should a pipeline with no steps do? With reduce and an initial value, it returns the input unchanged, which is the identity function and the correct answer.

JavaScript
console.log(pipeline()("unchanged"));
Text
unchanged

Providing the initial value matters. Without it, reduce on an empty array throws TypeError: Reduce of empty array with no initial value, and on a non-empty array it would use the first step as the starting value, which is not what you want here.

Named steps and useful errors

When a step fails, the stack points into an anonymous arrow function, and the real question is which step it was. Give each step a name and report it.

JavaScript
function namedPipeline(steps) {
  return (input) =>
    steps.reduce((value, [name, fn]) => {
      try {
        return fn(value);
      } catch (cause) {
        throw new Error(`step "${name}" failed on ${JSON.stringify(value)}`, { cause });
      }
    }, input);
}

const parseUser = namedPipeline([
  ["parse", (text) => JSON.parse(text)],
  ["check", (user) => {
    if (!user.email) throw new TypeError("email required");
    return user;
  }],
  ["domain", (user) => ({ ...user, domain: user.email.split("@")[1] })],
]);

console.log(parseUser('{"email":"[email protected]"}'));

try {
  parseUser('{"name":"Ada"}');
} catch (error) {
  console.log(error.message);
  console.log(error.cause.message);
}
Text
{ email: '[email protected]', domain: 'example.com' }
step "check" failed on {"name":"Ada"}
email required

The error names the step and shows the value it received, and cause keeps the original. Logging the value is a decision to make carefully: it is excellent for debugging and a risk if the value is sensitive, so truncate or redact it for real data.

Steps that can drop a value

In a data pipeline over a list, some steps remove items. In a pipeline of single values, a step may want to say "nothing here, stop". Reuse a sentinel and make reduce respect it. Since reduce cannot break out of the loop, short-circuit by checking the sentinel at the top of each step.

JavaScript
const SKIP = Symbol("skip");

function skippable(steps) {
  return (input) =>
    steps.reduce((value, step) => (value === SKIP ? SKIP : step(value)), input);
}

const parseAge = skippable([
  (s) => s.trim(),
  (s) => (s === "" ? SKIP : s),
  (s) => Number(s),
  (n) => (Number.isNaN(n) ? SKIP : n),
  (n) => n + 1,
]);

console.log(parseAge(" 41 "));
console.log(parseAge("   ") === SKIP);
console.log(parseAge("abc") === SKIP);
Text
42
true
true

After a step returns SKIP, every later step is bypassed, so the n + 1 never sees a NaN or an empty string. The array is still walked to the end, which is cheap for a short pipeline. If you need a real early exit for a very long list of steps, a for loop with return is the better tool, and it is fine to say so: reduce is a convenience, not a requirement.

Async steps

With a promise as the accumulator, reduce chains asynchronous steps.

JavaScript
const pipelineAsync = (...steps) => (input) =>
  steps.reduce((promise, step) => promise.then(step), Promise.resolve(input));

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

const enrich = pipelineAsync(
  (id) => wait(5, { id }),
  (user) => wait(5, { ...user, name: `user-${user.id}` }),
  (user) => user.name.toUpperCase(),
);

console.log(await enrich(7));
Text
USER-7

Each then receives the resolved value of the previous step. Synchronous and asynchronous steps mix freely, because then accepts a plain return value as well as a promise. A rejection anywhere skips the remaining steps and rejects the final promise, which is the behavior you want. This builds the whole chain at once and runs it in sequence, so each step starts when the previous one settles.

Transforming a whole collection

Real data pipelines work on lists: filter some rows, map the rest, then sum. The idea is the same, but the steps are array methods.

JavaScript
const orders = [
  { id: 1, status: "paid", amount: 40 },
  { id: 2, status: "refunded", amount: 15 },
  { id: 3, status: "paid", amount: 25 },
  { id: 4, status: "paid", amount: 10 },
];

const filterStep = (pred) => (list) => list.filter(pred);
const mapStep = (fn) => (list) => list.map(fn);
const reduceStep = (fn, init) => (list) => list.reduce(fn, init);

const paidTotal = pipeline(
  filterStep((o) => o.status === "paid"),
  mapStep((o) => o.amount),
  reduceStep((sum, n) => sum + n, 0),
);

console.log(paidTotal(orders));
Text
75

Three paid orders of 40, 25 and 10 sum to 75. Each step is a small reusable function that returns a function of the list, so the pipeline reads like a description of the work. One performance point is worth knowing: every step creates a new array. For a short list that is nothing, and for millions of rows the intermediate arrays cost memory. In that case, switch to a single loop, or to iterator helpers, which process one item at a time without building intermediate arrays.

JavaScript
const total = orders
  .values()
  .filter((o) => o.status === "paid")
  .map((o) => o.amount)
  .reduce((sum, n) => sum + n, 0);

console.log(total);
Text
75

Iterator helpers are available in Node.js 22 and later, and they are lazy: each order flows through filter and map before the next one is read, so no intermediate array exists. The result is the same.

Passing context along

Sometimes a step needs more than the previous value, for example a configuration or a logger. Do not widen every function's signature. Close over the context when you build the pipeline.

JavaScript
function makePipeline(config) {
  return pipeline(
    (n) => n * config.factor,
    (n) => Math.min(n, config.max),
  );
}

console.log(makePipeline({ factor: 3, max: 20 })(5));
console.log(makePipeline({ factor: 3, max: 20 })(10));
Text
15
20

The configuration is fixed when the pipeline is created, and the steps stay plain functions of one argument, so they compose and test the same way as before.

Designing steps that compose

A pipeline is only as good as its steps, and a few habits keep them reusable. Each step should take one argument and return one value, so it fits anywhere. A step that needs extra parameters is written as a function that returns a step, as filterStep(pred) does above, which is the same idea as currying. A step should not modify its input: return a new value, so that running the pipeline twice on the same data gives the same answer and the original stays available for comparison.

Keep steps small and named by what they do, not how, such as normalizeEmail and not lowercaseAndTrim. When a pipeline grows past eight or ten steps, group related steps into a smaller pipeline and use it as one step in the larger one, since a pipeline is itself a function of one argument. That nesting is what makes the pattern scale: the top-level pipeline reads like an outline, and each part can be tested alone.

Finally, resist adding side effects such as logging or saving in the middle of the chain. Put them at the end, or wrap them in a step that returns its input unchanged, so the data path stays easy to follow.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("an empty pipeline returns its input", () => {
  assert.equal(pipeline()(5), 5);
});

test("steps run in order", () => {
  assert.equal(pipeline((n) => n + 1, (n) => n * 10)(1), 20);
});

test("a failing step is named in the error", () => {
  const run = namedPipeline([["boom", () => { throw new Error("x"); }]]);
  assert.throws(() => run(1), /step "boom" failed/);
});

test("skippable stops further steps", () => {
  let reached = false;
  const run = skippable([() => SKIP, () => { reached = true; }]);

  assert.equal(run(1), SKIP);
  assert.equal(reached, false);
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.