Reputation: 586
I am currently going through 'Javascript: The good parts' by Douglas Crockford, an there is an example demonstrating the concept of memoization.
var memoizer = function (memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};
var fibonacci = memoizer([0, 1], function (shell, n) {
return shell(n - 1) + shell(n - 2);
});
What I don't understand is, where is the value for n
coming from?
Upvotes: 3
Views: 228
Reputation: 4755
In the code var shell = function (n)
, you're specifying that when you call the function shell
, you're going to provide it with an input argument n
. So if you called shell(5)
, n
would be equal to 5, or any other number that you passed in.
You need to look at what's being called and returned in each function call -- fibonacci
is set to the returned value of the memoizer
function, and memoizer
returns the shell
function which takes in n
. So although it's never called in your example code, in the end you'd call, say, fibonacci(5)
where 5 is your n
. Just follow the function calls and returns.
Upvotes: 1
Reputation: 239291
n
is an input. It doesn't "come" from any where in the code you've posted, you have to supply it a value.
Upvotes: 1