function memorize (f, hasher) {
var memo = function (name) {
var cache = memo.cache;
var key = "" + (hasher ? hasher.apply(this.arguments) : name);
if (!cache[key]) {
cache[key] = f.apply(this, arguments);
}
}
memo.cache = {};
return memo;
}
function add (a, b) {
return a + b;
}
var memorizedAdd = memorize(add, function () {
var args = Array.prototype.slice.call(arguments);
return JSON.stringify(args)
})
console.log(memorizedAdd(1, 2)) // 3
console.log(memorizedAdd(1, 2)) // 不经过计算直接得出3
网友评论