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:

  1. function* fibonacci(): The key is using function*. This declares a generator function.

  2. Variables: We initialize variables a and b to start the Fibonacci sequence (0 and 1).

  3. while (true) Loop: Generates an infinite loop for continuous Fibonacci numbers.

  4. yield a;: The yield keyword pauses execution and "yields" the current value of a. When you call next() on the generator, it resumes from this point, giving you the yielded value.

  5. [a, b] = [b, a + b];: Updates a and b 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 with value (the yielded number) and done (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