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:
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