实现函数功能如下:
将add函数缓存起来
function add(a,b){
return a+b
}
1.定义了一个cache对象用于缓存计算值,使用闭包将cache保存起来,保证函数执行完后cache不会被垃圾回收机制回收。
2.在memorize函数内部return一个函数用于接收参数,通过比对cache的键值来查看是否已经计算过,如果没有计算过,调用fn.apply来计算。
const memorize = function(fn){
var cache = {}
return function (){
var key = JSON.stringify(arguments)
if(cache[key]){
console.log("存在缓存,直接取值")
return cache[key]
}else{
cache[key] = fn.call(fn,...arguments)
console.log("没有缓存,执行函数")
return cache[key]
}
}
}
测试
const addcache = memorize(add)
console.log(addcache(1, 2));
console.log(addcache(1, 2));
console.log(addcache(2, 3));
结果: