JavaScriptFundamental (ES6), part 1
Why a generator can only be used once in JavaScript
56 A generator is its own iterator, so it runs out
fairSpread the same generator object twice and report what the second spread gives you. Show that a break closes it permanently. Then make an object and a class that can be looped as often as you like, by handing back a fresh generator each time.
Stuck? Three hints, smallest first
- 1. A generator object’s
[Symbol.iterator]()returnsthis, so it is the iterator, not a factory of iterators. - 2. Breaking out of a
for...ofcalls the iterator’sreturn(), which finishes a generator for good. - 3. The fix is one level of indirection: an object whose
[Symbol.iterator]is itself a generator method.
function* stops() {
yield 'Oshodi';
yield 'Ikeja';
}
const gen = stops();
const isOwnIterator = gen[Symbol.iterator]() === gen;
const firstSpread = [...gen];
const secondSpread = [...gen]; // empty: already drained
let loopsRun = 0;
for (const stop of gen) loopsRun++; // body never entered
const split = stops();
const pulledOne = split.next().value;
const remainder = [...split]; // resumes, does not restart
const closedByBreak = stops();
const beforeBreak = [];
for (const stop of closedByBreak) {
beforeBreak.push(stop);
break; // calls return() on the generator
}
const afterBreak = [...closedByBreak];
const route = {
*[Symbol.iterator]() { // a NEW generator per call
yield 'Oshodi';
yield 'Ikeja';
},
};
class Line {
constructor(...stops) { this.stops = stops; }
*[Symbol.iterator]() {
for (const stop of this.stops) yield stop;
}
}
const line = new Line('Yaba', 'Surulere');
console.log('own iterator? :', isOwnIterator);
console.log('first spread :', firstSpread, '| second:', secondSpread);
console.log('for...of after :', loopsRun, 'iterations');
console.log('split :', pulledOne, remainder);
console.log('break then read:', beforeBreak, afterBreak);
console.log('route twice :', [...route], [...route]);
console.log('class twice :', [...line], [...line]);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a generator object hands back itself as its iterator', isOwnIterator, true);
test('so the first spread drains it', firstSpread, ['Oshodi', 'Ikeja']);
test('and the second gets nothing, with no error to warn you', secondSpread, []);
test('a for...of over an exhausted generator runs zero times', loopsRun, 0);
test('a partly read generator resumes rather than restarting', [pulledOne, remainder], ['Oshodi', ['Ikeja']]);
test('breaking out of a for...of closes the generator permanently', [beforeBreak, afterBreak], [['Oshodi'], []]);
test('an object with a generator method gives a fresh iterator each time', [[...route], [...route]], [['Oshodi', 'Ikeja'], ['Oshodi', 'Ikeja']]);
test('and so does a class, so an instance can be looped as often as you like', [[...line], [...line]], [['Yaba', 'Surulere'], ['Yaba', 'Surulere']]);
test('the class instance still stores plain data beside it', Object.keys(line), ['stops']);
The distinction is iterable against iterator. An iterator has a cursor and is used up; an iterable is something that can hand out iterators. A generator object is both, and its [Symbol.iterator]() returns itself — so passing one to two consumers does not give them a sequence each, it splits one sequence between them, and passing an exhausted one gives the second consumer an empty loop with no complaint. That silence is the bug: no error, just nothing.
The break case catches people who assume a paused generator can be resumed later. for...of is tidy on exit: it calls return() on the iterator, which runs any finally in the generator and closes it. Useful for releasing a resource, fatal if you meant to come back. The cure for both problems is to expose an iterable — an object or class with a *[Symbol.iterator]() method — and let each consumer call it. Arrays, Maps, Sets and strings all work that way, which is why you can loop them twice without thinking about it.