Implement a custom iterator in JavaScript that iterates over Fibonacci numbers.

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.

Updated

Official answer available

Read the opening below, then unlock the full answer and practical guidance.

Absolutely, I'd be happy to dive into that. Firstly, to clarify, the Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In implementing a custom iterator for this sequence, we're essentially creating an object that adheres to the JavaScript iterator protocol. This protocol requires the object to have a next() method that returns an object with two properties: value, the next Fibonacci number in the sequence, and done, a boolean indicating if the iteration is complete. Given the infinite nature of Fibonacci numbers, done will perpetually be false in our case.

const fibonacciIterator = { [Symbol.iterator]() { let [prev, curr] = [0, 1]; return { next() { [prev, curr]...

Related Questions