I came upon this simplified example of a memoization function in JavaScript. It's then used to memoize a function that adds 2 to whatever number is passed in. When I saw this, it didn't seem obvious that the memoize
function would continue to store the cache
variable after being ran since it's not a property of memoize
, just (seemingly) an ordinary local variable. Shouldn't it be overridden whenever memoize
is called via plusTwo
? Where can I find out more about this behavior in JavaScript?
var memoize = function(function_) {
var cache = {};
return function() { // What does this function do?
//makes a string out of the arguments of the function that was passed in
var arg_str = JSON.stringify(arguments);
/*
sets the cache value for the arguments to the value that was already calculated
(if available) or calculates the value for the passed in function on its
*/
cache[arg_str] = cache[arg_str] || function_.apply(function_, arguments);
console.log(cache);
// returns the calculated (or cached) value
return cache[arg_str];
};
};
var plusTwo = memoize(function (x) {
return x + 2;
});
module.exports = memoize, plusTwo;