let memoize = function (func) {
/*
此处执行的是 [memoize] 自身方法
仅调用一次,多次调用会覆盖cache
*/
let cache = Object.create(null);
return function (key, ...arg) {
/*
执行 [add] 函数
key:第一个参数
将函数的返回结果存储到cache中
*/
cache[key] = func.apply(func, arg);
return cache[key]
}
}
function add(num1, num2) {
return num1 + num2
}
//使用
let foo = memoize(add)
let res = foo(‘key‘, 1, 2)
let res1 = foo(‘key‘, 2, 3)
console.log(res + res1);
原文:https://www.cnblogs.com/venlong/p/15181462.html