0

I'm trying to write my own fibonacci function. It should return all fibonacci numbers that are smaller than num in an array. I tried checking currentPush against num with a while loop, but it pushes one value too much to the returned array.

Whats wrong with my code? It should stop before the last iteration because currentPush is definitely bigger than num.

function fib(num) {

  if(num < 2){return 1};

  let fib = [1, 1];
  let currentPush = 2;

  while (currentPush < num){
    // get last two elements from array and add them together
    currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    fib.push(currentPush);
  }

  return fib;
}
 console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
 console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]
Nick Frost
  • 37
  • 6
  • 1
    You change `currentPush` inside the loop *after* the test. – Pointy May 31 '19 at 16:47
  • because currentPush is calculated to be greater.... You check it after you push it on next iteration. if less, then do this, calculate value, push value, check if less..... repeat. Code does not immediately exit once it is greater, it finishes that loop and then stops. – epascarello May 31 '19 at 16:48
  • 1
    @AnandGhaywankar 13 is geater than 10.... – epascarello May 31 '19 at 16:51
  • Ohhh, I get it … Damn. I switched the lines in the `while` loop and now it works. I push first, then change the currentPush and if it doesn't match the while condition, it exits. Is that right? Thank you! – Nick Frost May 31 '19 at 16:52

1 Answers1

1

As the comments mention, you'll have to check for currentPush < num before pushing to the array but after computing currentPush

function fib(num) {

  if(num < 2) {return 1};

  let fib = [1, 1];
  
  while (true) {
    let currentPush = fib.slice(fib.length-2, fib.length).reduce((a, b) => a + b);
    if (currentPush > num)
      return fib;
    fib.push(currentPush);
  }
}

console.log(fib(10)); // [ 1, 1, 2, 3, 5, 8, 13 ]
console.log(fib(100)); // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 ]
junvar
  • 11,151
  • 2
  • 30
  • 46
  • Thank you! Easily comprehensible code! Interesting use of a while loop. Is that common practice? – Nick Frost May 31 '19 at 16:59
  • It's pretty common when your condition has to be checked after some of the loop body is computed. The alternative would be to duplicate the `currentPush` computation both before the while loop and inside, which would be frowned upon. – junvar May 31 '19 at 17:14