You're right - that version is over-complicated. A simplified version would work just as well:
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.