简体   繁体   中英

Memoization in Javascript from Crockford's book

Example 1.

var fibonacci = function () {
  var memo = [0, 1];
  var fib = function (n) {
    var result = memo[n];

    if (typeof result !== 'number') {
      result = fib(n - 1) + fib(n - 2);
      memo[n] = result;
    }

    return result;
  };

  return fib;
}();
  

Example 2.

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);
});

Above are 2 code snippets from Crockford's book to demonstrate the concept of memoization.

Question 1. How do I invoke function fibonacci from any of 2 examples? By usual way fibonacci (5) ?

Question 2. As I can see, argument "n" is not defined anywhere when calling var fib = function (n) { or var shell = function (n) { .In the first example of fibonacci function I'd expect "n" to be defined right after the 2nd line var memo = [0, 1]; , and I'd expect "n" to be defined as follows: n = arguments[0]; . However since this doesn't seem to be the case, so I have to ask: how is "n" determined when fibonacci is invoked?

Thanks.

Page from Crockford's books

Question 1: How do I call each one?

The first example, note the }() at the end. This is invoking the function, which in turn gives the fib function back. So fibonacci() in the first example is really fib() with it's own internal references (eg memo and fib ), memo only being accessible by fib but lasting as a reference as long as a reference to fib exists (the variable holding fibonacci 's return).

The second example is similar, except it's substituting a memoizer that accepts an array of items and returns shell , which has access to the array it was passed.

Question 2: What is n as an argument doing?

Since you're really calling a reference to an internally created but externally available fib() and shell() when you call either fibonacci function, you're passing in a new number, which then has it's fibonacci sequence "memoized" by storing it in the internally available memo given at the beginning.


The point is that memoization is like a hash store where computations already known (since they were previously performed and "memoized") are accessible (preventing re-computation), and using Javascript's closure construct allows you to use internally-scoped variables to manage that access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM