bhansa
bhansa

Reputation: 7504

Fibonacci generator not giving correct results

function* fib() {
  a = 0;
  b = 1;
  while (true) {
    yield a;
    a = b;
    b = a + b;
  }
}

let f = fib();
let index = 0;
for(let i of f){
  if(index > 14){
    break;
  }
  console.log(i);
  index++;
}

Output: 0 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192

What am I doing wrong here?

Upvotes: 0

Views: 72

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370799

You're overwriting a, so on the next line, b = a + b doesn't give the right calculation for the new value of b.

Either save it in a separate variable before reassigning, or use destructuring to swap them at once:

function* fib() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

let f = fib();
let index = 0;
for(let i of f){
  if(index > 14){
    break;
  }
  console.log(i);
  index++;
}

(this works because the [b, a + b] expression on the right is completely evaluated before the assignment for [a, b] = occurs)

Also, best to avoid implicitly declare global variables - consider enabling strict mode and/or using a linter, else that sort of thing may result in bugs.

Upvotes: 3

Related Questions