Reputation: 389
I am trying to figure out closure in Javascript.
Trying to calculate fibonacci series using DP. Here my input will be index: Index = 10 And the output: 55 (As per fibonacci seq: 0,1,1,2,3,5,8,13,21,34,55..)
Below version is a working code:
function recursiveDynamicProgramming(){
let cache = {};
//use javascript closure method
return function getFib(n){
//var getFib = function(n){ : When i assign function to this variable. I am getting undefined error. Although it has return value :(
if(n in cache){//if(cache[n])
return cache[n];
} else{
if(n < 2){
return n;
}else{
cache[n] = getFib(n - 2) + getFib(n - 1);
return cache[n];
}
}
}
}
const dynamicProdFib = recursiveDynamicProgramming();
console.log(dynamicProdFib(10)); //Output = 55, Input = 10
//console.log(dynamicProdFib.getFib(10)); //This should give me the same result as the variable getFib is defined in the program.
So here if you can refer the commented code where
//var getFib = function(n){ : When i assign function to this variable. I am getting undefined error.
Although it has return value //Or we can use this.getFib = function(n)
But when i try to call this method I am getting undefined error. Which simply means my function is not returning a value. But i am returning value inside this function. I am not sure where i am making mistake.
We have several examples of this question but i am not able to wrap my head around this. Please pardon me for this. Thank you for the help :)
UPDATE: Thanks @Bergi for pointing my silly mistake.
In my case i am trying to call the output like :
dynamicProdFib.getFib(10)
so i have to put the output in an object:
return {getFib};
Or simply call the output as:
return dynamicProdFib(10)
Hope this is helpful :)
Upvotes: 0
Views: 225
Reputation: 664777
That you are return
ing inside the getFib
function is not enough, the part you were missing is that you also need to return
the getFib
function from recursiveDynamicProgramming
. It might help to introduce a helper variable for that though:
function recursiveDynamicProgramming() {
let cache = {};
var getFib = function(n) { // or just "function getFib(n) {"
…
};
return getFib;
// ^^^^^^^^^^^^^^
}
Upvotes: 1