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
function*andyieldproduce values on demand.- An infinite generator is safe when consumed lazily.
- Spreading a generator collects what it yields.
Keywords and builtins used here
constforfunctionifletofreturnwhileyield
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.
Step 1 of 2 in Generators, step 10 of 16 in Functions & patterns.