Iterator Helpers Are Lazy And Single-Pass

Iterator helpers chain filter, take, and map lazily, but the resulting iterator is single-pass: a drained chain yields nothing on a second consumption.

TypescriptData Integrity

Code

typescriptsnippet
33 lines
// Iterator helpers are lazy and single-pass: TS 5.6 tracks every step's type,
// but the chain itself can only be consumed once.
interface DeployEvent {
  level: 'error' | 'info';
  message: string;
  code: number;
}

const events: DeployEvent[] = [
  { level: 'error', message: 'disk full', code: 507 },
  { level: 'info', message: 'deploy started', code: 200 },
  { level: 'error', message: 'health check failed', code: 503 },
  { level: 'info', message: 'deploy finished', code: 200 },
  { level: 'error', message: 'cache miss storm', code: 504 },
];

// filter -> take -> map wraps a fresh iterator from events.values()
const errors = events.values()
  .filter((event) => event.level === 'error')
  .take(2)
  .map((event) => `${event.code} ${event.message}`);

// First pass drains the chain
console.log('first two errors:', [...errors]);

// A second pass yields nothing: iterators do not restart
console.log('after drain:', errors.toArray());

// Fresh chains run again; materialize with toArray to keep an array
const errorCount = events.values()
  .filter((event) => event.level === 'error')
  .toArray().length;
console.log('error count:', errorCount);

Output

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

first two errors: [ '507 disk full', '503 health check failed' ]
after drain: []
error count: 3

What the code does

Top-level bindings errors, errorCount hold the demo state — nothing sits inside a function scope.

What to watch for

  • Any imports it has point exclusively at standard-library modules.

Using it

Watch for labeled lines in the run — first two errors:, after drain:, error count: — when the file runs.

Key statements

.map((event) => `${event.code} ${event.message}`);
.filter((event) => event.level === 'error')
.toArray().length;

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Its state lives in module-level bindings: `errors`, `errorCount`.