Generator Pull Based Pipeline

Chain generator stages so data is pulled item by item on demand — memory stays flat for huge or infinite sources without arrays.

JavascriptResilience

Code

javascriptsnippet
33 lines
function* numbers(from, to) {
  for (let i = from; i <= to; i++) yield i;
}

function* filter(source, predicate) {
  for (const value of source) {
    if (predicate(value)) yield value;
  }
}

function* map(source, transform) {
  for (const value of source) {
    yield transform(value);
  }
}

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

// 组合管道:take(5) 决定实际拉动量,上游按需逐个产出
const pipeline = take(
  map(filter(numbers(1, 1_000_000), (n) => n % 3 === 0), (n) => n * n),
  5,
);

for (const value of pipeline) {
  console.log(value);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

9
36
81
144
225

How the snippet works

The nesting pairs for (let i = from; i <= to; i++) yield i; with for (const value of source) — the inner runs once per outer step.

Module-level bindings hold the data — pipeline — with no function scope in between.

What to watch for

  • The guard taken++ >= count cuts the flow short with an early return when its condition holds.

Key statements

for (let i = from; i <= to; i++) yield i;
if (predicate(value)) yield value;
yield transform(value);

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `pipeline`.