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
- The method returns an iterator with a
next. - A generator is the easy way to write one.
Symbol.asyncIteratoris the same idea forfor await.
Keywords and builtins used here
MathSymbolbreakclassconstconstructorforfromifletofreturnthisyield
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.
Step 2 of 2 in Iterating asynchronously, step 11 of 19 in Promises & async.