typestar

The iterable protocol in JavaScript

Anything with Symbol.iterator works in for-of and spread.

class Countdown {
  constructor(from) {
    this.from = from;
  }

  *[Symbol.iterator]() {
    for (let n = this.from; n > 0; n -= 1) yield n;
  }
}

const countdown = new Countdown(4);
console.log([...countdown], Math.max(...countdown));

for (const n of countdown) {
  if (n === 2) break;
  console.log("tick", n);
}

const manual = {
  [Symbol.iterator]() {
    let n = 0;
    return { next: () => (n < 2 ? { value: n++, done: false }
                                : { value: undefined, done: true }) };
  },
};
console.log([...manual]);

How it works

  1. The method returns an iterator with a next.
  2. A generator is the easy way to write one.
  3. Symbol.asyncIterator is the same idea for for await.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
479
Tokens
165
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 2 in Iterating asynchronously, step 11 of 19 in Promises & async.

← Previous Next →