let worker = {
someMethod() {
return 12;
},
slow(x) {
// 可怕的 CPU 过载任务
// alert("Called with " + x);
return x * this.someMethod(); // (*)
}
};
// console.log(slow(2))
function getUniq(args){
return args.reduce((result, cur)=> result += `,${cur}`, '');
}
function withCache(func) {
// 缓存
const cache = new Map();
return function(...args){
const key = getUniq(args);
if(cache.has(key)) {
console.log('read from cache')
return cache.get(key);
} else {
let result = func.apply(this, args);
cache.set(key, result);
return result;
}
}
}
const faster = withCache(worker.slow.bind(worker));
console.log(faster(2));
console.log(faster(2));
console