javascript · level 3 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Generators are , so they can describe endless sequences.
An array must hold every value at once. A generator is lazy: it works out each value only when asked. So a generator can safely contain a loop that never ends, because it pauses at every yield.
The trick is to take only what you need. take stops after count values, and squares changes each value as it passes. Stack helpers like these into a , and each value flows through every step before the next one is even made.
function* naturals() {
let n = 0;
while (true) { n++; yield n; }
}
function* squares(items) { for (const n of items) { yield n * n; } }
function* take(items, count) {
for (const item of items) {
if (count === 0) { return; }
count--;
yield item;
}
}
console.log([...take(squares(naturals()), 5)]); Never spread an endless generator on its own: with no take in front, it would never stop.
guess first
An endless loop meets a break. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function* numbers() {
let n = 0;
while (true) {
n++;
console.log(`made ${n}`);
yield n;
}
}
for (const n of numbers()) {
if (n === 2) { break; }
console.log(`used ${n}`);
}
your turn
Your turn. Stripe a table with endless colours.
Add a third colour to the cycle. Watch the colours start again from the beginning once all three are used.
fix it
Asked for 3, got 4. Can you fix it?
- One value too many. When does the check on
counthappen: before or after a value goes out? - The check runs after
yield, so one extra value slips out beforetakenotices. - Move
yield item;belowcount--;, so the check runs first, then press run.
nailed it
you tamed an endless sequence. :D
- Generators are lazy: each value is made only when asked.
- An endless loop is safe in a generator that yields.
- Use a helper like
taketo stop after enough values.
new words in your collection
- lazy
- pipeline
This lesson isn’t saved. A free account remembers every lesson you finish.