Question 35
Question
Answer
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 onLast updated