I was reading Professor Frisby's Mostly adequate guide to functional programming and I came across this code example shown below. I don't understand why cache is not reset to {} each time squareNumber is called.
var memoize = function(f){
var cache = {}; // why is this not reset each time squareNumber is called?
return function() {
var arg_str = JSON.stringify(arguments);
cache[arg_str] = cache[arg_str]|| f.apply(f, arguments);
return cache[arg_str];
};
}
var squareNumber = memoize(function(x){ return x*x; });
squareNumber(4);
//=> 16
squareNumber(4); // returns cache for input 4
//=> 16
squareNumber(5);
//=> 25
squareNumber(5); // returns cache for input 5
//=> 25
One theory I have is that since memoize is a global variable the cache variable is not reset every time it is called. But I can't seem to find a good solution.