typestar

Generators in JavaScript

Functions that yield a stream of values lazily.

function* idMaker(start = 1) {
  let id = start;
  while (true) {
    yield id++;
  }
}

function* take(iterable, n) {
  let i = 0;
  for (const value of iterable) {
    if (i++ >= n) return;
    yield value;
  }
}

const ids = [...take(idMaker(100), 3)];

How it works

  1. function* and yield produce values on demand.
  2. An infinite generator is safe when consumed lazily.
  3. Spreading a generator collects what it yields.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
231
Tokens
77
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 44 seconds.

Type this snippet

Step 1 of 2 in Generators, step 10 of 16 in Functions & patterns.

← Previous Next →