Skip to content
jshacks.dev
Functions

How to Use Function Composition in Data Pipelines

Use function composition to clean, validate and summarize CSV-style data in JavaScript, keep bad rows with a Result type and report errors per row. Node.js 24.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite and npm logos.

A data pipeline takes messy input and produces something you can trust: a CSV export becomes validated records, a list of events becomes a report. The temptation is to write it as one long function with loops, flags and special cases. A composition-based pipeline splits it into small functions that each do one thing, and the real work is in deciding what happens to a row that fails halfway. Throw an exception and the whole batch dies on row 4,000. Drop it silently and you ship wrong totals. This post builds a realistic pipeline on Node.js 24: parse lines into rows, clean fields, validate, convert and aggregate, with a small Result type so that bad rows are kept and reported instead of lost. For the reduce mechanism underneath, see building a pipeline of transformations with reduce.

The input

A text export of orders, with some problems built in: stray spaces, a missing amount, a negative quantity and a malformed line.

JavaScript
const raw = `
id,customer,amount,qty
1, Ada ,12.50,2
2,Linus,abc,1
3,  Grace,8,-1
4,Brendan,20,3
broken line
5,Guido,5.25,4
`;

Parsing it into row objects is the first function. It does no validation, only structure.

JavaScript
const parseLines = (text) => {
  const [header, ...lines] = text.trim().split("\n");
  const keys = header.split(",");

  return lines.map((line, index) => {
    const cells = line.split(",");
    return { line: index + 2, cells, keys };
  });
};

const rows = parseLines(raw);

console.log(rows.length);
console.log(rows[0]);
Text
6
{
  line: 2,
  cells: [ '1', ' Ada ', '12.50', '2' ],
  keys: [ 'id', 'customer', 'amount', 'qty' ]
}

The output has 6 rows, because the broken line is a row like any other at this stage. Each row carries its original line number, so every later error can say where the data came from, and that number is the cheapest piece of context in the whole pipeline.

Why exceptions are the wrong default

Suppose the next function converts a row into a record and throws on bad data.

JavaScript
const toRecordThrowing = ({ line, cells, keys }) => {
  if (cells.length !== keys.length) throw new Error(`line ${line}: expected ${keys.length} cells`);

  const amount = Number(cells[2]);

  if (Number.isNaN(amount)) throw new Error(`line ${line}: amount is not a number`);

  return { id: Number(cells[0]), customer: cells[1].trim(), amount, qty: Number(cells[3]) };
};

try {
  rows.map(toRecordThrowing);
} catch (error) {
  console.log(error.message);
}
Text
line 3: amount is not a number

The map stopped at the first failure, on line 3, and the good rows after it were never processed. Wrapping everything in try/catch per row works but pushes error handling into every step. A cleaner design lets each step return either a value or an error as data, and lets the pipeline carry both.

A small Result type

A Result is an object that is either { ok: true, value } or { ok: false, error }. Two constructors and a function that applies a step only to the good ones are enough.

JavaScript
const ok = (value) => ({ ok: true, value });
const fail = (error) => ({ ok: false, error });

const then = (result, fn) => (result.ok ? fn(result.value) : result);

console.log(then(ok(2), (n) => ok(n * 10)));
console.log(then(fail("earlier"), (n) => ok(n * 10)));
Text
{ ok: true, value: 20 }
{ ok: false, error: 'earlier' }

then applies the function to a successful result and passes a failure along untouched, so a chain of steps stops doing work for a row after its first failure while the error stays attached. No exceptions, no flags. It is the same idea as promise chaining, applied to plain values.

The steps

Write each step as a function from a value to a Result. Each does one check and names the line in its message.

JavaScript
const checkShape = (row) =>
  row.cells.length === row.keys.length
    ? ok(row)
    : fail(`line ${row.line}: expected ${row.keys.length} cells, got ${row.cells.length}`);

const toObject = (row) =>
  ok({ line: row.line, ...Object.fromEntries(row.keys.map((key, i) => [key, row.cells[i].trim()])) });

const convert = (r) => {
  const amount = Number(r.amount);
  const qty = Number(r.qty);

  if (Number.isNaN(amount)) return fail(`line ${r.line}: amount "${r.amount}" is not a number`);
  if (!Number.isInteger(qty)) return fail(`line ${r.line}: qty "${r.qty}" is not an integer`);

  return ok({ line: r.line, id: Number(r.id), customer: r.customer, amount, qty });
};

const validate = (r) => (r.qty > 0 ? ok(r) : fail(`line ${r.line}: qty must be positive, got ${r.qty}`));

Compose them with a helper that threads a Result through a list of steps.

JavaScript
const pipeResult = (...steps) => (input) =>
  steps.reduce((result, step) => then(result, step), ok(input));

const processRow = pipeResult(checkShape, toObject, convert, validate);

const results = rows.map(processRow);

for (const result of results) {
  console.log(result.ok ? `ok   line ${result.value.line}` : `fail ${result.error}`);
}
Text
ok   line 2
fail line 3: amount "abc" is not a number
fail line 4: qty must be positive, got -1
ok   line 5
fail line 6: expected 4 cells, got 1
ok   line 7

Every row was processed. Three succeeded, and three failed with a message that names the line and the reason. The bad rows did not stop the good ones, and the failures are collected instead of lost. The order of the steps matters: the shape is checked before the cells are read, so broken line fails with a clear message and not with a TypeError from reading a missing cell.

The then helper is what composes the steps. It is a hand-rolled version of what functional languages call a monad's bind, and the name does not matter. What matters is the behavior: a failure short-circuits the remaining steps for that row only.

Splitting good from bad

After the row-level work, separate the two groups. The good rows continue to aggregation, and the bad rows become a report.

JavaScript
const partition = (results) => ({
  good: results.filter((r) => r.ok).map((r) => r.value),
  errors: results.filter((r) => !r.ok).map((r) => r.error),
});

const { good, errors } = partition(results);

console.log(good.map((r) => r.customer));
console.log(errors.length);
Text
[ 'Ada', 'Brendan', 'Guido' ]
3

Whether to continue when some rows failed is a policy decision, and it belongs outside the row functions. A report on yesterday's orders may be fine with a few skipped rows and a warning. A payment batch must stop if any row is bad. Keeping the failures as data means that choice is a single if (errors.length > 0) in the caller.

Aggregating the good rows

Aggregation is also a composition of small functions.

JavaScript
const lineTotal = (r) => r.amount * r.qty;
const sum = (list) => list.reduce((a, b) => a + b, 0);
const round2 = (n) => Math.round(n * 100) / 100;

const byCustomer = (list) =>
  Object.fromEntries(list.map((r) => [r.customer, round2(lineTotal(r))]));

const summary = {
  rows: good.length,
  revenue: round2(sum(good.map(lineTotal))),
  perCustomer: byCustomer(good),
};

console.log(summary);
Text
{
  rows: 3,
  revenue: 106,
  perCustomer: { Ada: 25, Brendan: 60, Guido: 21 }
}

Ada's row is 12.50 * 2 = 25, Brendan's is 20 * 3 = 60 and Guido's is 5.25 * 4 = 21, summing to 106. Rounding to cents is done once at each output, since adding floating-point amounts directly can produce values such as 0.30000000000000004, and a financial pipeline should either round at the end or store amounts as integer cents from the start.

Putting the whole pipeline together

Each stage is a function, and the whole job is a composition of them.

JavaScript
function runPipeline(text) {
  const { good, errors } = partition(parseLines(text).map(processRow));

  return {
    summary: { rows: good.length, revenue: round2(sum(good.map(lineTotal))) },
    errors,
  };
}

console.log(runPipeline(raw));
Text
{
  summary: { rows: 3, revenue: 106 },
  errors: [
    'line 3: amount "abc" is not a number',
    'line 4: qty must be positive, got -1',
    'line 6: expected 4 cells, got 1'
  ]
}

Both outputs come from one pass. The summary covers the valid rows and the errors name each rejected line.

Choosing where to put each concern

A pipeline stays readable when each stage has one job, and the hard part is deciding which job goes where. Parsing deals with structure only: it turns text into rows and does not judge the values. Cleaning fixes harmless problems such as stray spaces and inconsistent case, because rejecting " Ada " would punish the sender for a cosmetic issue. Validation decides whether a row is acceptable at all, and it should run after conversion, so the rule can say "quantity must be positive" about a number instead of about text. Aggregation comes last and trusts its input, because everything it receives has already passed.

Resist the urge to merge stages for speed. A function that parses, converts and validates at once is shorter on the page and longer to debug: when a total is wrong you cannot tell which responsibility failed. Separate stages also let you reuse them. The same convert step works for a CSV file, an API response and a spreadsheet import, while only the first stage differs.

Scaling to large inputs

The version above builds an array at every stage, which is fine for a few thousand rows. For a file with millions of lines, hold one row at a time. A generator for each stage, or iterator helpers such as lines.values().map(processRow), passes a row through the whole chain before reading the next, so memory stays flat no matter how large the file is. The Result type works unchanged, because it is only a value, and you can count successes and collect the first hundred errors as the rows stream past instead of keeping all of them.

For files that do not fit in memory at all, read with a stream from node:fs and split on newlines, feeding each line into the same composed function. The composition is the part that does not change, which is the practical reward of writing the stages as small functions in the first place.

Testing a pipeline

Because each step is a pure function, each is tested with a handful of inputs and no fixtures or mocks.

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

test("convert rejects a non-numeric amount", () => {
  const result = convert({ line: 9, id: "1", customer: "x", amount: "abc", qty: "1" });

  assert.equal(result.ok, false);
  assert.match(result.error, /line 9/);
});

test("a failure skips the later steps", () => {
  let reached = false;
  const run = pipeResult(() => fail("stop"), () => { reached = true; return ok(1); });

  assert.equal(run(0).ok, false);
  assert.equal(reached, false);
});

test("the pipeline keeps good rows and reports bad ones", () => {
  const { summary, errors } = runPipeline(raw);

  assert.equal(summary.rows, 3);
  assert.equal(errors.length, 3);
});
Text
ℹ tests 3
ℹ pass 3
ℹ 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.