Skip to content

Replace Loop with Pipeline: Turn Loops into map, filter and reduce

Learn how to replace a loop that filters, transforms and accumulates data with a readable map/filter/reduce pipeline, step by step, in TypeScript, Python and PHP.

7 min readRefactoring

Replace Loop with Pipeline takes a hand-written loop that skips some elements, transforms others and adds things up, and rewrites it as a chain of named collection operations: filter, map and reduce, or comprehensions in Python. The result reads top to bottom as a description of the data flow instead of a set of instructions for moving values between mutable variables. Interviewers like this refactoring because it shows you can spot accumulator patterns, keep behaviour identical while restructuring, and reason about cost and ordering. This guide walks through a warehouse restocking example in three languages.

The problem

A situation where the obvious design starts to hurt.

Larkspur Tools runs a small warehouse service. Every night a job calls buildRestockPlan with about 4,000 stock items. It must ignore discontinued items, ignore items at or above their reorder point, and for everything else order enough units to reach twice the reorder point. It returns one text line per order plus the total number of units.

The current version is a single loop with two continue guards, a calculation, a push into a list and a running total. Each concern is easy on its own, but they are interleaved, so you have to simulate the loop in your head to know what ends up in lines and totalUnits. When the purchasing team asked for an extra rule (skip items with an open purchase order), the developer had to work out where in the loop body it was safe to add another continue.

Before and after

The same code, before and after the change.

Before

interface StockItem {
  sku: string;
  onHand: number;
  reorderPoint: number;
  discontinued: boolean;
}

interface RestockPlan {
  lines: string[];
  totalUnits: number;
}

function buildRestockPlan(items: StockItem[]): RestockPlan {
  const lines: string[] = [];
  let totalUnits = 0;
  for (const item of items) {
    if (item.discontinued) {
      continue;
    }
    if (item.onHand >= item.reorderPoint) {
      continue;
    }
    const units = item.reorderPoint * 2 - item.onHand;
    lines.push(`${item.sku}: order ${units}`);
    totalUnits += units;
  }
  return { lines, totalUnits };
}

const plan = buildRestockPlan([
  { sku: "HX-204", onHand: 3, reorderPoint: 10, discontinued: false },
  { sku: "DR-118", onHand: 0, reorderPoint: 5, discontinued: true },
  { sku: "BL-550", onHand: 12, reorderPoint: 8, discontinued: false },
  { sku: "SC-031", onHand: 7, reorderPoint: 8, discontinued: false },
]);
console.log(plan); // { lines: [ 'HX-204: order 17', 'SC-031: order 9' ], totalUnits: 26 }

After

interface StockItem {
  sku: string;
  onHand: number;
  reorderPoint: number;
  discontinued: boolean;
}

interface RestockPlan {
  lines: string[];
  totalUnits: number;
}

function buildRestockPlan(items: StockItem[]): RestockPlan {
  const orders = items
    .filter((item) => !item.discontinued)
    .filter((item) => item.onHand < item.reorderPoint)
    .map((item) => ({ sku: item.sku, units: item.reorderPoint * 2 - item.onHand }));

  return {
    lines: orders.map((order) => `${order.sku}: order ${order.units}`),
    totalUnits: orders.reduce((sum, order) => sum + order.units, 0),
  };
}

const plan = buildRestockPlan([
  { sku: "HX-204", onHand: 3, reorderPoint: 10, discontinued: false },
  { sku: "DR-118", onHand: 0, reorderPoint: 5, discontinued: true },
  { sku: "BL-550", onHand: 12, reorderPoint: 8, discontinued: false },
  { sku: "SC-031", onHand: 7, reorderPoint: 8, discontinued: false },
]);
console.log(plan); // { lines: [ 'HX-204: order 17', 'SC-031: order 9' ], totalUnits: 26 }

Why it's worth it

What the change buys you.

A loop body mixes three different jobs: deciding which elements matter, computing something from each one, and collecting results into mutable variables. A pipeline gives each job its own stage with its own name. filter says which items survive, map says what each survivor becomes, and reduce or sum says how the results combine. You can read each stage without tracking how continue statements and accumulators interact.

The pipeline also removes mutable state. lines and totalUnits are no longer variables that change on every iteration; they are values derived from orders. That makes the two outputs independent, so adding the open purchase order rule from the problem means inserting one more filter line, with no risk of accidentally skipping the push but not the total.

The complexity stays O(n). The pipeline makes a few passes over the data instead of one and allocates intermediate arrays, which is a constant-factor cost that rarely matters for a few thousand items. Behaviour, including output order, is unchanged because filter and map preserve the original order.

  • Each stage names one intent, so the selection rules, the calculation and the aggregation can be read and changed separately.
  • Mutable accumulators disappear, which removes a common source of bugs where one output is updated and another is not.
  • New rules become a single extra filter stage rather than a carefully placed continue.
  • The intermediate orders collection is a natural seam for testing or for extracting a reusable function later.

Careful with

  • Pipelines make several passes and allocate intermediate arrays. Complexity stays O(n), but in a tight hot path over millions of elements, measure before and after.
  • Keep callbacks free of side effects. A map that writes to a log, mutates the item or calls an API hides behaviour that a loop at least made visible.
  • Loops that break early or search for one element do not map onto filter/map/reduce; use find, some, any() or next() instead, or keep the loop.
  • In PHP, array_filter preserves the original keys, so call array_values before relying on a zero-indexed list or encoding to JSON.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure tests cover the function: a mix of discontinued items, items at exactly the reorder point, items above it and items below it, asserting both the lines and the total. Run them and keep them green.

  2. Introduce a variable orders above the loop that holds items unchanged, and make the loop iterate over orders instead. Run the tests.

  3. Move the discontinued guard into the pipeline as a filter (or comprehension condition) and delete the matching continue. Run the tests.

  4. Move the reorder point guard into a second filter, inverting the condition so it keeps items with onHand < reorderPoint, and delete its continue. Run the tests; the boundary case where stock equals the reorder point catches an inverted comparison.

  5. Add a map stage that turns each item into an order with sku and units, and change the loop body to read order.units instead of recomputing it. Run the tests.

  6. Replace the line-building half of the loop with orders.map(...) assigned to lines, leaving only the running total inside the loop. Run the tests.

  7. Replace the running total with reduce (or sum in Python), then delete the now empty loop and the mutable variables. Run the tests a final time.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

Why does the Python version use comprehensions instead of map and filter?

Comprehensions are the idiomatic pipeline in Python. A list comprehension with if clauses is a filter followed by a map, and sum() over a generator is the reduce. Using map and filter with lambdas works but reads worse to most Python reviewers, and functools.reduce for a plain sum is considered unidiomatic.

Is a pipeline always better than a loop?

No. If the loop body has complex control flow, early exits, or updates several unrelated pieces of state in ways that depend on each other, forcing it into a pipeline can make it harder to read. The refactoring pays off when the loop is a recognisable filter, transform and accumulate pattern, which is the common case.

How would I explain this refactoring in an interview?

Describe the loop's three jobs, show how each becomes a stage, and say how you kept behaviour identical: tests first, one guard moved at a time, boundary cases checked when inverting a condition. Then mention the trade-off honestly: still O(n), a few extra passes and allocations, usually irrelevant compared with the readability gain.

Next guide7 of 7 · Techniques: composing functionsReplace Function with Command: Turn a Long Function into an ObjectRead the next one