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 ]