Lab 06: Iterators & Generators
Overview
Step 1: Iterator Protocol
// An iterator is any object with a next() method
const manualIterator = {
items: ['a', 'b', 'c'],
index: 0,
next() {
if (this.index < this.items.length) {
return { value: this.items[this.index++], done: false };
}
return { value: undefined, done: true };
}
};
console.log(manualIterator.next()); // { value: 'a', done: false }
console.log(manualIterator.next()); // { value: 'b', done: false }
console.log(manualIterator.next()); // { value: 'c', done: false }
console.log(manualIterator.next()); // { value: undefined, done: true }
// Built-in iterables
const arr = [1, 2, 3];
const iter = arr[Symbol.iterator]();
console.log(iter.next()); // { value: 1, done: false }
console.log(iter.next()); // { value: 2, done: false }
// String is iterable
for (const char of 'hello') {
process.stdout.write(char + ' ');
}
console.log(); // h e l l oStep 2: Custom Iterable
Step 3: Generator Functions (function*)
Step 4: yield* and Delegation
Step 5: Infinite Sequences
Step 6: Two-way Communication
Step 7: Async Generators
Step 8: Capstone — Lazy Pipeline
Summary
Concept
Syntax
Use Case
Last updated
