I wrote a memoize function for Javascript today to cache file timestamps. I thought I would share it with the world. Here is the code:
function memoize(f){
var cache = {}
return function(){
var keys = []
for (var i = 0; i < arguments.length; i++){
keys.push(typeof(arguments[i]) + ':' + String(arguments[i]))
}
var key = keys.join('/')
if (key in cache){
return cache[key]
}else{
var val = f.apply(null, arguments)
cache[key] = val
return val
}
}
}
Let's say you have a function:
function f(x, y){
return x + y * 2
}
If you memoize it:
f = memoize(f)
The first time you call f with arguments (3, 4):
f(3, 4) => 11
It will compute it, but the second time:
f(3, 4) => 11
It will merely return the cached value computed from the last time.
Note about the implementation: the equality metric used by this memoize function is: 2 objects are equal iff they are of the same type:
typeof(one) == typeof(other)
and, they have the same string represention:
String(one) == String(other)
That is it. Enjoy!