Reputation: 121
this maybe is not the biggest challenging problem but I've got curious about it. I did a simple code just to get the Fibonacci value based on the user input without recursion and works just fine. Very simple code:
function fib(n) {
let fibArray = [0,1];
let count = 0;
while(fibArray.length <= n){
let previous = fibArray[count + 1];
let beforePrevious = fibArray[count];
fibArray.push(beforePrevious + previous);
count++;
}
return fibArray[n];
}
But the moment I tried to make it as a recursive function, the result is undefined, even if the value is not.
function fib(n, count = 0, fibArray = [0,1]){
if(fibArray.length - 1 === n){
return fibArray[n];
}
if (fibArray.length <= n ) {
let previous = fibArray[count + 1];
let beforePrevious = fibArray[count];
fibArray.push(beforePrevious + previous);
count++;
}
fib(n,count, fibArray);
}
Upvotes: 0
Views: 45
Reputation: 571
The code is ok, you just need to add a return:
function fib(n, count = 0, fibArray = [0,1]){
if(fibArray.length - 1 === n){
return fibArray[n];
}
if (fibArray.length <= n ) {
let previous = fibArray[count + 1];
let beforePrevious = fibArray[count];
fibArray.push(beforePrevious + previous);
count++;
}
return fib(n,count, fibArray);
}
Upvotes: 2
Reputation: 386654
Just add a return
statement in the last line.
return fib(n,count, fibArray);
Upvotes: 2