Skip to content

Lazy Pipelines

The Course
•
20 min study

Array.map eagerly creates a result array. A generator transformation can instead yield one transformed value for each requested input. Compose small synchronous generators to filter and map a source without materializing intermediate arrays.

Laziness changes when side effects happen and when errors become visible. A pipeline can be constructed successfully but fail only when consumed. A consumer that asks for one result should not cause the entire source to be processed. This is useful for large finite data sources and bounded workers.

Do not confuse laziness with low total memory in every API. Spreading the entire pipeline into an array collects everything. An infinite source still cannot be fully collected. Likewise, the final task pool bounds active mapper calls but retains all output for ordered return; it is not a streaming-output API.

Use explicit loops inside generator helpers while learning. The yield sites show exactly which work happens for each request, and generator cleanup composes with early loop exit.

Predict, run, and explain

Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.

Predict, then run JavaScript
function* doubled(values) {
  for (const value of values) {
    console.log(`read ${value}`);
    yield value * 2;
  }
}

const pipeline = doubled([1, 2, 3]);

console.log("created");
console.log(pipeline.next().value);
pipeline.return();
Check your prediction
Text
created
read 1
2

Observe work that a consumer never requested

A lazy transform performs work only as downstream demand advances it. This can avoid processing unused items, but it also changes when effects and errors occur. A function returning an iterator has not necessarily completed its calculations when it returns.

Composition order matters. Filtering before transforming can reduce mapper calls; transforming before filtering may be required if the predicate depends on the transformed value. Preserve the intended values and order before claiming an optimization.

Observe work that a consumer never requested: trace JavaScript
let calls = 0;

function* doubled(values) {
  for (const value of values) {
    calls++;
    yield value * 2;
  }
}

const cursor = doubled([1, 2, 3]);

console.log(calls);
console.log(cursor.next().value);
console.log(calls);
cursor.return();
Check your prediction
Text
0
2
1

Only one transformation ran. The unused inputs never reached the multiplication. This is useful evidence of laziness, beyond merely returning an object with next.

Observe work that a consumer never requested: contrast JavaScript
const values = [1, 2, 3, 4];
let first = 0;
let second = 0;
const a = values
  .filter(n => n > 2)
  .map(n => {
    first++;
    return n * 2;
  });
const b = values
  .map(n => {
    second++;
    return n * 2;
  })
  .filter(n => n > 4);

console.log(a.join(","), b.join(","));
console.log(first, second);
Check your prediction
Text
6,8 6,8
2 4

These predicates are deliberately equivalent for this transformation. Equal outputs do not mean equal work. For a different predicate or effectful mapper, reordering may change the contract.

Try the rule on new inputs

Count mapper calls for zero, one and all requested outputs. Add a failure on a later unused input and explain when it should become observable. Do not confuse lazy input consumption with constant result memory.

Compose stages and watch the reads interleave

Each stage below is a generator that reads from the one inside it. take(2, map(..., filter(..., source))) reads inside-out: the outer take asks map for a value, map asks filter, and filter reads the array. The log.push lines are only there so you can see which stage runs when. Predict the order of the log entries before running, then compare it with the same steps written as an eager array chain.

Three stages, one item at a time JavaScript
const log = [];

function* filter(test, values) {
  for (const value of values) {
    log.push(`filter ${value}`);
    if (test(value)) yield value;
  }
}

function* map(transform, values) {
  for (const value of values) {
    log.push(`map ${value}`);
    yield transform(value);
  }
}

function* take(count, values) {
  if (count <= 0) return;
  let taken = 0;
  for (const value of values) {
    yield value;
    taken += 1;
    if (taken === count) return;
  }
}

const source = [1, 2, 3, 4, 5, 6];

const lazy = take(2, map(n => n * 10, filter(n => n % 2 === 0, source)));
console.log([...lazy].join(","));
console.log(`lazy:  ${log.join(" | ")}`);

log.length = 0;
const eager = source
  .filter(n => {
    log.push(`filter ${n}`);
    return n % 2 === 0;
  })
  .map(n => {
    log.push(`map ${n}`);
    return n * 10;
  })
  .slice(0, 2);
console.log(eager.join(","));
console.log(`eager: ${log.join(" | ")}`);
Check your prediction
Text
20,40
lazy:  filter 1 | filter 2 | map 2 | filter 3 | filter 4 | map 4
20,40
eager: filter 1 | filter 2 | filter 3 | filter 4 | filter 5 | filter 6 | map 2 | map 4 | map 6

Both chains print 20,40, but the logs differ. In the lazy chain each value travels through every stage before the next one is read: 1 stops at the filter, 2 goes on to map, and so on. Once take has two values it returns, so 5 and 6 are never read. The eager chain runs each stage over the whole array before the next begins: six filter calls, then three map calls (including 6, whose result slice throws away). Read take as the stage that creates demand. Its check comes after the yield, so it never asks its source for a value it will not use.

Trace the contract before building

Ask when each source value is requested. A lazy map should transform only enough input to satisfy current demand. A filter may need several source values for one output, while a take-like boundary should stop requesting once its quota is satisfied.

Trace a source with a visible pull count and ask for one result before collecting the rest. Creating the pipeline should not eagerly consume it. Conversely, spreading the completed pipeline intentionally materializes all results, so laziness alone makes no promise about final retained memory. Keep demand, transformation and output storage as separate parts of the API contract.

Your turn

Exercise

Two stages and a closing source

readAll(values, log) is supplied: it logs each read and logs source closed from its finally. Write two more stages. keep(test, values) yields only the values that pass test. label(values) yields #1:ant, #2:bee... numbering the values it receives, so skipped blanks do not use up a number. The supplied firstTwo breaks after two results. Building the pipeline must read nothing, and the break must reach the source's finally. Print:

Text
after building: 0 reads
#1:ant #2:bee
read "ant", read "", read "bee", source closed
Your workspace JavaScript
function* readAll(values, log) {
  try {
    for (const value of values) {
      log.push(`read ${JSON.stringify(value)}`);
      yield value;
    }
  } finally {
    log.push("source closed");
  }
}

function* keep(test, values) {
  // yield only the values that pass test
}

function* label(values) {
  // yield `#${position}:${value}`, counting from 1
}

function firstTwo(iterable) {
  const results = [];
  for (const value of iterable) {
    results.push(value);
    if (results.length === 2) break;
  }
  return results;
}

const log = [];
const words = ["ant", "", "bee", "  ", "cat", "dog"];
const pipeline = label(keep(word => word.trim() !== "", readAll(words, log)));

console.log(`after building: ${log.length} reads`);
console.log(firstTwo(pipeline).join(" "));
console.log(log.join(", "));
Hint 1: the idea

Each stage is a for...of over the stage inside it, with a yield where a value should pass outwards. The numbering belongs to label, so the counter lives in label and only advances when label actually receives a value.

Hint 2: a first step

Write keep first, with label yielding each value unchanged. Run it: you should see ant bee and a log that stops at read bee followed by source closed. Then add the counter to label.

Show one solution
JavaScript
function* readAll(values, log) {
  try {
    for (const value of values) {
      log.push(`read ${JSON.stringify(value)}`);
      yield value;
    }
  } finally {
    log.push("source closed");
  }
}

function* keep(test, values) {
  for (const value of values) {
    if (test(value)) yield value;
  }
}

function* label(values) {
  let position = 0;
  for (const value of values) {
    position += 1;
    yield `#${position}:${value}`;
  }
}

function firstTwo(iterable) {
  const results = [];
  for (const value of iterable) {
    results.push(value);
    if (results.length === 2) break;
  }
  return results;
}

const log = [];
const words = ["ant", "", "bee", "  ", "cat", "dog"];
const pipeline = label(keep(word => word.trim() !== "", readAll(words, log)));

console.log(`after building: ${log.length} reads`);
console.log(firstTwo(pipeline).join(" "));
console.log(log.join(", "));
Text
after building: 0 reads
#1:ant #2:bee
read "ant", read "", read "bee", source closed

Calling the three generator functions builds the chain but runs no bodies, so there are 0 reads. firstTwo pulls through label and keep into readAll; the empty strings are read and dropped by keep without ever reaching label, which is why the numbers stay #1, #2. The break calls return() on label. That ends label's own for...of, which calls return() on keep, which calls it on readAll, so the source's finally runs even though firstTwo only holds the outermost iterator. cat and dog are never read.

Change it and test it

Add a transformation that squares each value, then compose it after positive. Log input reads and stop after one yielded result. Which values were actually examined? Explain how this differs from mapping and filtering an entire array first.

Was this article helpful?

Your response is saved on this device.