Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Lazy pipelines with Iterator helpers

Use iterator helpers to collect the first two matching records from a generator without reading its remaining values or building intermediate arrays.

You need the first two failed jobs from a stream of results. Collecting the generator into an array first reads every job. Chain filter(), map(), and take() to read just far enough to find the two IDs.

Let the consumer request values

On a runtime with iterator helpers, a generator inherits those methods. Each helper returns an iterator. The source starts running when a consumer such as toArray() asks for its first value.

function* jobs() {
  try {
    for (const [id, failed] of [
      [1, false],
      [2, true],
      [3, false],
      [4, true],
      [5, true],
    ]) {
      console.log('read', id)
      yield { id, failed }
    }
  } finally {
    console.log('closed')
  }
}

const failedIds = jobs()
  .filter((job) => job.failed)
  .map((job) => job.id)
  .take(2)

console.log('collect')
console.log(failedIds.toArray())

You see collect first, then reads for jobs 1 through 4, then closed and [2, 4]. The source never reads job 5.

diagram

Source reads per collector request

The filter reads four jobs to find two failed IDs, and the next pull closes the generator before job 5.

The first request passes through take(2) and map() to filter(). The filter needs two source reads before it finds a match. After the second ID, the collector pulls once more to check for completion. The limit closes the source with its return() method, which runs the generator's finally.

Put the limit after the filter

The order defines which count you limit. In this pipeline, take(2) counts matching jobs. Move it before filter() and it counts source records. Only job 2 would survive that version because the source would stop after job 2.

Use for…of instead of toArray() if you can act on each ID as it arrives. The final array here stores two IDs, and there are no intermediate arrays of matches. The source may still run to exhaustion if it yields fewer matches than the limit.

failedIds is a one-use iterator. A second call to toArray() returns an empty array. Start with a fresh jobs() call when you need to replay the pipeline. For a custom object with next() but no helper methods, use Iterator.from(source) to get a helper-capable iterator.