Sub topic 2
Building a Custom Iterable by Hand
This chapter assumes you know the iterable and iterator protocols: Symbol.iterator returns an object whose next() produces { value, done }. It also assumes you are comfortable with classes and closures.
Building a Custom Iterable by Hand
To make an object iterable, give it a [Symbol.iterator]() method that returns an iterator. Each call should return a fresh iterator so the object can be looped over more than once. Making the iterator iterable too (its own [Symbol.iterator] returns this) lets it work directly in for...of.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
if (current < end) {
return { value: current++, done: false };
}
return { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
}
};
}
}
console.log([...new Range(1, 4)]); // [ 1, 2, 3 ]Early Exit and the return() Method
When a loop stops early through break, return, or a thrown error, for...of calls the iterator's optional return() method. That is where an iterator should close files or release locks.
function withCleanup(items) {
let i = 0;
return {
[Symbol.iterator]() { return this; },
next() {
return i < items.length
? { value: items[i++], done: false }
: { value: undefined, done: true };
},
return() {
console.log('cleanup');
return { value: undefined, done: true };
}
};
}
for (const x of withCleanup([1, 2, 3])) {
if (x === 2) break; // logs 'cleanup'
}Generator Functions and How They Run
A generator function (function*) returns a generator object, which is an iterator. Calling the function does not run its body. Each next() runs the body until the next yield, then pauses. A return value arrives with done: true, so for...of and spread skip it.
function* count() {
yield 1;
yield 2;
return 3;
}
const g = count(); // the body has not run yet
console.log(g.next()); // { value: 1, done: false }
console.log(g.next()); // { value: 2, done: false }
console.log(g.next()); // { value: 3, done: true }
console.log(g.next()); // { value: undefined, done: true }
console.log([...count()]); // [ 1, 2 ]Writing Iterables with Generators
A generator method replaces the hand-built iterator. The generator tracks state and the done flag for you.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i < this.end; i++) yield i;
}
}
console.log([...new Range(1, 4)]); // [ 1, 2, 3 ]Delegating with yield*
yield* passes along every value from another iterable. The yield* expression itself evaluates to the delegated generator's return value.
function* inner() {
yield 'a';
yield 'b';
return 'inner done';
}
function* outer() {
const result = yield* inner();
yield result;
yield* [1, 2];
}
console.log([...outer()]); // [ 'a', 'b', 'inner done', 1, 2 ]Exercise
In the generator version of Range, what does const r = new Range(0, 2); console.log([...r], [...r]); print, and why?
Show answer
It prints [ 0, 1 ] [ 0, 1 ]. Each spread calls r[Symbol.iterator](), which creates a new generator object, so every pass starts again from the beginning.