Module 52 : Iterators and Generators
1.Introduction
What is an Iterator?
An iterator is an object that allows you to traverse through a collection (like arrays, strings, etc.) one item at a time. It follows the iterator protocol, which requires:
A next() method
That returns an object: { value: any, done: boolean }
const myIterator = { next: function() { return { value: ..., done: false }; // Until done is true } };
What is Iterable?
An iterable is any object that has a method Symbol.iterator which returns an iterator.
Built-in iterables: Arrays, Strings, Maps, Sets
2. Creating a Custom Iterator
Let’s build a simple iterator that counts from 1 to 5:
function createCounter(limit) { let count = 1; return { next: function() { if (count <= limit) { return { value: count++, done: false }; } else { return { done: true }; } } }; } const counter = createCounter(5); console.log(counter.next()); // { value: 1, done: false } console.log(counter.next()); // { value: 2, done: false } console.log(counter.next()); // { value: 3, done: false }
3. Making an Object Iterable
const range = { start: 1, end: 5, [Symbol.iterator]() { let current = this.start; let end = this.end; return { next() { if (current <= end) { return { value: current++, done: false }; } else { return { done: true }; } } }; } }; for (let num of range) { console.log(num); // 1 2 3 4 5 }
}
Explanation:
We defined [Symbol.iterator]() method
It returns an object with next() function
The for...of loop uses that protocol behind the scenes
4. Generators – Simplifying Iterators
📖 Definition:
Generators are special functions defined with function* and use the yield keyword to produce a sequence of values on demand.
function* simpleGenerator() { yield 1; yield 2; yield 3; } const gen = simpleGenerator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false }
Advantages of Generators
Feature
Benefit
yield
Pause and resume execution
Lazy Evaluation
Save memory, load values only when needed
Clean Syntax
Avoid boilerplate in iterator construction
5. Generator Example: Fibonacci Sequence
function* fibonacci(limit) { let a = 0, b = 1; let count = 0; while (count < limit) { yield a; [a, b] = [b, a + b]; count++; } } for (let num of fibonacci(7)) { console.log(num); // 0 1 1 2 3 5 8 }
6. Use Cases
Use Case
Explanation
Pagination
Load results page by page using generators
Stream Reading
Lazy read large files using generators
Game States
Generators for state-based game logic
Infinite Scroll
Use iterators to stream content on demand
7. Exercises
🔹 Exercise 1: Custom Iterable Object
Create an object that iterates over even numbers from 2 to 10.
const evens = { [Symbol.iterator]() { let num = 2; return { next() { if (num <= 10) { return { value: num++, done: false }; } else { return { done: true }; } } }; } }; for (let val of evens) { if (val % 2 === 0) console.log(val); // 2 4 6 8 10 }
🔹 Exercise 2: Generator to Yield Square Numbers
function* squareGenerator(n) { for (let i = 1; i <= n; i++) { yield i * i; } } for (let square of squareGenerator(5)) { console.log(square); // 1 4 9 16 25 }
🔹 Exercise 3: Infinite Generator
function* infiniteCounter() { let count = 1; while (true) { yield count++; } } const counter = infiniteCounter(); console.log(counter.next().value); // 1 console.log(counter.next().value); // 2
8. Deep Dive
Under the Hood
When you use a for...of loop:
for (let value of iterable) {}
JavaScript does:
let iterator = iterable[Symbol.iterator](); let result = iterator.next(); while (!result.done) { let value = result.value; result = iterator.next(); }
9. Research
From ES6 Specification:
Introduced the Symbol.iterator to formalize custom iteration
Generators based on coroutines pattern (inspired from Python, Lua)
Industry Usage:
Company
Use Case
Netflix
Streams video content chunk by chunk using generators
React
Uses iterables in virtual DOM diffing logic
Node.js
Uses generators in libraries like co for async flow before async/await
10. Summary
Iterators define how to traverse a data structure
The Symbol.iterator protocol makes any object iterable
Generators simplify writing iterators using yield
They allow lazy execution and are powerful for sequences
Ideal for streaming, pagination, state machines
11. Work
Create a generator that yields a multiplication table of a given number up to 10.
Make a custom iterable for a deck of cards.
Write a generator to simulate turns in a two-player game (alternate yields).
No comments:
Post a Comment