Instruction: Write a custom iterator that generates an infinite sequence of Fibonacci numbers.
Context: This question tests the candidate's understanding of the iterator protocol and their ability to implement custom iterable objects.
Official answer available
Preview the opening of the answer, then unlock the full walkthrough.
const fibonacciIterator = { [Symbol.iterator]() { let [prev, curr] = [0, 1]; return { next() { [prev, curr] = [curr, prev + curr]; return { value: prev, done: false }; } }; } };
Let me break down the approach here. We start by defining an object fibonacciIterator that implements the [Symbol.iterator]() method, making it compliant with the iterable protocol. This method returns an iterator, an object with the next() method. In next(), we update prev and curr to move through the Fibonacci sequence, then return the current Fibonacci number as the...