JavaScriptFundamental (ES6), part 2
Reusable iterables vs one-shot iterators in JavaScript
11 An iterable you can loop over twice
fairMake a class whose instances can be iterated more than once. Then build the broken version that caches a single generator and show that its second pass is empty. Work out which of the two protocols — iterable or iterator — each one implements.
Stuck? Three hints, smallest first
- 1. A generator method named
[Symbol.iterator]returns a fresh generator on every call. - 2. An iterable hands out an iterator; an iterator has
next(). A generator object is both, and that is the confusion. - 3. An array is re-iterable. The iterator you get from an array is not.
class Ledger {
constructor(rows) { this.rows = rows; }
*[Symbol.iterator]() { for (const row of this.rows) yield row; }
}
const broken = {
rows: [1, 2, 3],
cached: null,
[Symbol.iterator]() {
if (!this.cached) this.cached = (function* (rows) { yield* rows; })(this.rows);
return this.cached; // the SAME iterator every time
},
};
const ledger = new Ledger([
{ item: 'rice, 50kg', naira: 45000 },
{ item: 'palm oil', naira: 12000 },
]);
const firstPass = [...ledger];
const secondPass = [...ledger];
const brokenPasses = [[...broken], [...broken]];
const arrayTwice = (() => { const a = [1, 2]; return [[...a], [...a]]; })();
const iteratorTwice = (() => { const it = [1, 2][Symbol.iterator](); return [[...it], [...it]]; })();
const [firstRow, secondRow] = new Ledger(['x', 'y']);
console.log('two passes over the ledger:', firstPass.length, secondPass.length);
console.log('two passes over the broken one:', brokenPasses);
console.log('array twice :', arrayTwice);
console.log('iterator twice:', iteratorTwice);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a generator method makes the object re-iterable', [firstPass.length, secondPass.length], [2, 2]);
test('and both passes see the same rows', firstPass, secondPass);
test('a cached generator makes it single-use', brokenPasses, [[1, 2, 3], []]);
test('an array is re-iterable, because values() is fresh each time', arrayTwice, [[1, 2], [1, 2]]);
test('but its iterator is not', iteratorTwice, [[1, 2], []]);
test('an array is not its own iterator', [1, 2][Symbol.iterator]() === [1, 2], false);
test('while a generator object is', (() => { const g = (function* () {})(); return g[Symbol.iterator]() === g; })(), true);
test('destructuring uses the same protocol', [firstRow, secondRow], ['x', 'y']);
Two protocols, one object, endless confusion. Iterable means "has [Symbol.iterator](), which returns an iterator". Iterator means "has next()". A generator object satisfies both, and its [Symbol.iterator]() returns this — which is exactly why it can only be looped once.
So the rule for anything you hand out: return a new iterator each time [Symbol.iterator] is called. A generator method does that automatically, because calling a generator function is what creates the generator object. The broken version above caches it and thereby implements "iterable" with iterator semantics, and the failure is silent — the first loop works perfectly and the second one sees an empty collection.
The array pair is the same lesson in built-in form. [...a] twice works; [...a[Symbol.iterator]()] twice does not. If a function accepts an iterable and loops it more than once, it has to document that, or take an array.