Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.02k stars 235 forks source link

实现内存函数缓存函数调用结果 #262

Open Sunny-117 opened 2 years ago

z1the3 commented 1 year ago
const cachedFn = (function (fn) {
  let cache = {};
  return function (...args) {
    argsKey = args.toString()
    if (argsKey in cache) {
      return cache[argsKey];
    }
    return (cache[argsKey] = fn.apply(this, args));
  };
})(fn);
Windseek commented 7 months ago

const map = new Map(); const cacheFn = function(fn) {

return function(...args) { if( map.get(args)) { return map.get(args) } return map.set(args, fn.appy(this, args)); } }

dizao006 commented 1 month ago
利用闭包进行缓存
function catach(fn) {
  let cache = new Map();
  return function (...args) {
    let key = JSON.stringify(args);
    if (cache.has(key)) {
      console.log("cache");
      return cache.get(key);
    } else {
      let data = fn.apply(this, args);
      cache.set(key, data);
      return data;
    }
  };
}

function expensiveFunction(x) {
  console.log("Computing...");
  return x * x;
}
let cacheAft = catach(expensiveFunction);
console.log(cacheAft(5));
console.log(cacheAft(5));