JavaScript, Generators. How to "drop" the break from the loop when the exit condition is not set?

So, I was combing through some JS and came across the following example for a simple Fibonacci calculator:

function* fibs() {
    var a = 0;
    var b = 1;

    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
}

var [first, second, third, fourth, fifth, sixth] = fibs();

    // first = 0
    // second = 1
    // third = 1
    // fourth = 2
    // fifth = 3
    // sixth = 5

      

No matter how many elements you put into the result array, the loop function is exactly the right number of times and exits. Never more, no less, no mistakes.

var [first, second] = fibs();  // Works great!
var [a, b, c, d, e, f, g, h, I, j, k, l] = fibs();  // Still works!

      

I've been combing through the documents, but I can't find anything that could hint at what is going on.

How does the generator know when to exit the loop and be done with it? There are no exit conditions, and nothing to suggest that it would do nothing but flee for eternity.

Many thanks.

EDIT # 1

Is there any other way to use this same generator to get the nth number in a sequence without a potentially huge array of results?

+3


source to share


1 answer


How does the generator know when to exit the loop and be done with it?

This is not true. The generator never leaves the loop. It's just that the destructuring assignment only calls the generator iterator X times (as many as the number of variables in the destructuring assignment). The iterator doesn't know that it's over, it just answers the "next" calls it receives.

It goes something like this:



function* fibs() {
    var a = 0;
    var b = 1;

    while (true) {
        yield a;
        [a, b] = [b, a + b];
    }
}

// Pseudo-destructuring:
let first, second, third;
{
    const iterator = fibs();
    first = iterator.next().value;
    second = iterator.next().value;
    third = iterator.next().value;
    // Now, our "destructuring" is done, so we just...don't call
    // the iterator anymore
}
console.log(first, second, third);
      

Run codeHide result


This is not a generator, but a destructuring assignment that sets a limit.

+4


source







All Articles