Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to understand Crockford's memoizer function. While I'm able to follow how it works, I don't quite understand the fundamental argument and the inner function shell and how he came up with fundamental(shell, n); and function(shell, n) {...}. I mean, if I were writing the code myself, what would lead me to the same conclusion?

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


Intuitively, I would do something like:

JavaScript
function memoizer(memo, someFormula) {
  var shell = function() {
    // check memo
    // if not in memo
        // run the formula - someFormula();
        // store result in memo
    // return result;
  return shell;
  }  
}

var fibonacci = memoizer([0, 1], function(n) {
  // return fibonacci formula
};


Admittedly, it's not recursive and I've left out the n argument. While I know that shell and fundamental are not the same, I'm confused with the overlap and how they relate to each other.

What I have tried:

I've used the debugger so I understand how it works but I still don't understand the motive behind the code.
Posted
Updated 29-Aug-17 7:24am
Comments
Graeme_Grant 28-Aug-17 20:33pm    
Have you tried contacting the author? Douglas Crockford's memoizer · GitHub[^] - He would be the most appropriate person to answer this question...

1 solution

You're right - that version is over-complicated. A simplified version would work just as well:
JavaScript
var memoizer = function(cachedResults, theRealFunction) {
    return function (n) {
        if (!cachedResults.hasOwnProperty(n)) {
            cachedResults[n] = theRealFunction(n);
        }
        
        return cachedResults[n];
    };
};

var fibonacci = memoizer([0, 1], function(n) {
    console.debug("fibonacci", n);
    return fibonacci(n - 1) + fibonacci(n - 2);
});

The shell parameter was added so that the recursive memoized function could call the memoized version of itself. But since that's already available, stored in the fibonacci variable, there's no need to pass it as a parameter.
 
Share this answer
 
Comments
KM8 29-Aug-17 22:19pm    
Thanks for that. I do like your code. It's more readable and intuitive.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900