JavaScriptFundamental (ES6), part 1
Make a class iterable with Symbol.iterator in JavaScript
53 Write your own Symbol.iterator
fairMake your own class iterable by giving it a [Symbol.iterator]() method that returns an object with a next. Prove it works with spread, destructuring and for...of with a break, and that a fresh iterator per call lets it be looped twice. Then write a range helper the same way.
Stuck? Three hints, smallest first
- 1.
next()returns{ value, done }. Consumers stop as soon asdoneis true. - 2. Keep the cursor in a closure inside the method, so each call to
[Symbol.iterator]()starts again from zero. - 3. A symbol-keyed method is not a string key, so
Object.keyswill not show it.
class Route {
constructor(...stops) {
this.stops = stops;
}
[Symbol.iterator]() {
let i = 0;
const stops = this.stops; // captured, so next() needs no this
return {
next: () => (i < stops.length
? { value: stops[i++], done: false }
: { value: undefined, done: true }),
};
}
}
const range = (from, to) => ({
[Symbol.iterator]() {
let n = from;
return { next: () => (n <= to ? { value: n++, done: false } : { value: undefined, done: true }) };
},
});
const route = new Route('Oshodi', 'Ikeja', 'Agege');
const walked = [...route];
const twice = [[...route].length, [...route].length];
const [first, ...rest] = route;
const upToIkeja = [];
for (const stop of route) {
if (stop === 'Ikeja') break; // stops pulling
upToIkeja.push(stop);
}
const firstResult = route[Symbol.iterator]().next();
const numbers = [...range(1, 4)];
const sum = numbers.reduce((a, b) => a + b, 0);
console.log('spread :', walked);
console.log('twice :', twice, '<- a fresh iterator each time');
console.log('destructured:', first, rest);
console.log('break :', upToIkeja);
console.log('first result:', firstResult, '| range:', numbers, 'sum', sum);
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('spread drives the iterator to done', walked, ['Oshodi', 'Ikeja', 'Agege']);
test('a fresh iterator per call means it can be consumed twice', twice, [3, 3]);
test('destructuring pulls through the same protocol', [first, rest], ['Oshodi', ['Ikeja', 'Agege']]);
test('break stops pulling, so the rest is never produced', upToIkeja, ['Oshodi']);
test('next() hands back a result object, in that key order', firstResult, { value: 'Oshodi', done: false });
test('an object literal can be iterable too, with nothing but a next', numbers, [1, 2, 3, 4]);
test('and once spread it is an ordinary array', sum, 10);
test('the symbol-keyed method is not a string key', Object.keys(route), ['stops']);
test('but it is there, under the symbol', typeof route[Symbol.iterator], 'function');
Iterability is a method, not a class you inherit from. Anything with a [Symbol.iterator]() returning an object with a next() works with spread, for...of, array and object destructuring, Array.from, new Map, new Set, Promise.all and yield* — the whole language, from one method.
The second assertion is the design decision. The cursor i lives inside [Symbol.iterator](), so every consumer gets its own, and the route can be walked as often as you like. Hoist i out to the instance, or return this, and the object becomes single-use: the second loop finds it already exhausted and yields nothing, with no error. That is precisely the behaviour of a generator, which is the next exercise but one. Note also that break is honoured by simply not calling next again — there is nothing to clean up here, but if your iterator held a file handle you would add a return() method for it.