I need to make a function generator that iterates over an infinite sequence, like the fibonacci sequence. It should return the next value in the sequence when called. I am given a function prototype:
function genfib() {
return function fib() {
}
}
it should be used like this:
var fib = genfib();
fib(); // -> returns 0
fib(); // -> returns 1
fib(); // -> returns 1
fib(); // -> returns 2
I am confused about what is executing every time I call fib()
. I tried to do something like
function genfib() {
var count = 1;
if (count === 1) {
count++;
yield 0;
}
else if (count === 2) {
count++;
yield 1;
}
var a = 0;
var b = 1;
return function fib() {
while(1) {
count = a + b;
a = b;
b = count;
yield count;
}
}
}
But it's not working. I don't know how to set it up to run the if/else
for the first two numbers in the fib
sequence and then run the while
loop once for each subsequent call.