Question 35
Question
How would you use generators to create a custom iterator?
Answer
Generators are perfect for writing custom iterators in JavaScript.
Here's how you would use them to build your own iterator:
function* fibonacci() {
let a = 0;
let b = 1;
while (true) { // Infinite loop
yield a; // Yield the current Fibonacci number
[a, b] = [b, a + b]; // Update for the next iteration
}
}
const fibGenerator = fibonacci();
console.log(fibGenerator.next()); // Output: { value: 0, done: false }
console.log(fibGenerator.next()); // Output: { value: 1, done: false }
console.log(fibGenerator.next()); // Output: { value: 1, done: false }
console.log(fibGenerator.next()); // Output: { value: 2, done: false }
// ... and so on
Explanation:
function* fibonacci()
: The key is usingfunction*
. This declares a generator function.Variables: We initialize variables
a
andb
to start the Fibonacci sequence (0 and 1).while (true)
Loop: Generates an infinite loop for continuous Fibonacci numbers.yield a;
: Theyield
keyword pauses execution and "yields" the current value ofa
. When you callnext()
on the generator, it resumes from this point, giving you the yielded value.[a, b] = [b, a + b];
: Updatesa
andb
for the next Fibonacci number in the sequence.
Using the Generator:
Create an instance of your generator:
const fibGenerator = fibonacci();
.Call
next()
repeatedly to get each value from the sequence.next()
returns an object withvalue
(the yielded number) anddone
(true when the sequence is exhausted).
Benefits:
Memory Efficiency: Generators don't calculate all Fibonacci numbers at once; they generate them on demand, saving memory.
Readability: The code clearly shows the logic for generating the sequence.
Lazy Evaluation: Values are produced only when needed.
Last updated