Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding input value in JavaScript memoized function

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?

like image 442
LogixMaster Avatar asked Jan 24 '26 01:01

LogixMaster


1 Answers

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.

like image 110
Sam Hanley Avatar answered Jan 26 '26 17:01

Sam Hanley