I'm working on creating a function generator that can iterate over an infinite sequence, similar to the fibonacci sequence. The goal is to have it return the next value in the sequence each time it's called. Here is the function prototype I've been given:
function genfib() {
return function fib() {
}
}
This is how it should be used:
var fib = genfib();
fib(); // -> returns 0
fib(); // -> returns 1
fib(); // -> returns 1
fib(); // -> returns 2
I'm struggling to understand what exactly happens each time I call fib()
. I attempted to change the function like this:
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;
}
}
}
Unfortunately, this approach isn't working as expected. I'm unsure of how to structure it so that it follows the initial conditions for the first two numbers in the Fibonacci sequence and then enters the while loop for subsequent calls.