Листинг
function memoize(fn, resolver) {
var memoized = function() {
var cache = memoized.cache,
key = resolver
? resolver.apply(this, arguments)
: +new Date() + '' + arguments[0];
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = fn.apply(this, arguments));
}
memoized.cache = {};
return memoized;
}
Пример
var fibonacci = memoize(function(n) {
return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
});
fibonacci(7); //return 13