I've put together a generator to calculate the Fibonacci numbers/sequence. However, it's not working as I expect. I've "transpiled" it from python but I don't know what it is in my JavaScript code that doesn't fit my logic as python does... Can anyone give me a hint on this?
Here's the code:
// Fibonacci generator
function* fibonacci() {
var a = 0;
var b = 1;
while (true) {
yield a;
a = b;
b = a + b;
}
}
// Instantiates the fibonacci generator
fib = fibonacci();
// gets first 10 numbers from the Fibonacci generator starting from 0
for (let i = 0; i < 10; i++) {
console.log(i + ' => ' + fib.next().value);
}
I think this is a matter of variable scope. I've just got this to work by doing so:
// Fibonacci generator
function* fibonacci() {
var a = 0;
var b = 1;
while (true) {
var current = a;
a = b;
b = current + a;
yield current;
}
}
// Instantiates the fibonacci generator
var fib = fibonacci();
// gets first 10 numbers from the Fibonacci generator starting from 0
for (let i = 0; i < 10; i++) {
console.log(i + ' => ' + fib.next().value);
}
However, I still don't understand why I need to declare a third variable ("current"), within my loop, to obtain the desirable result. Any ideas?
EDIT: You guys are right. The problem is the variables were being assigned in two steps and therefore not getting the desired values. Here's the final, working code, that I decided to post for future reference:
// Fibonacci generator
function* fibonacci() {
[a, b] = [0, 1]
while (true) {
yield a;
[a, b] = [b, a + b]
}
}
// Instantiates the fibonacci generator
var fib = fibonacci();
// gets first 10 numbers from the Fibonacci generator starting from 0
for (let i = 0; i < 10; i++) {
console.log(fib.next().value);
}
Thank you very much!
b = a + byou have already seta = b, so this is justb = 2 * b. You may want to do[ a, b ] = [ b, a + b ]instead, to do the two assignments simulatenously (like in Python).