如何记忆函数,因此相同的参数从缓存返回



我的功能缓慢

function f(a, b, c) {
}

我有时会以相同的参数调用此功能,它将返回相同的结果。我想用参数缓存此函数调用,因此第二个带有同一参数从缓存返回的调用。

我尝试过,但它不起作用。

export function memoize(fn) {
  let cache;
  let res;
  return function(...args) {
    if (!cache) {
      cache = args;
      res = fn(...args);                                                                                                                      return res;
    }
    if (objectCompare(args, cache)) {
      return res;                                                                                                                           }
    return res = fn(...args);
  };
}             

要使用cache,我们需要将参数映射到结果。由于您有多个参数,因此您需要为这些参数生成一个唯一的密钥。例如,如果您有3个参数:a,b,c-可以创建一个键: $ {a} - $ {b} - $ {c}`(这只是一个示例,唯一重要的事情是这个键将是唯一的!(

演示(有关其他说明,请参见代码计算(:

function f(a, b, c) {
    return a + b + c; // for example
}
const memoized = (function(fn) {    // we'll wrap the original function
    const cache = {}; // init a cache
    return (a, b, c) => {
        const key = `${a}-${b}-${c}`; // create a key
        if (cache.hasOwnProperty(key)) { // search if it's already saved in the cache
            console.log('in memory');
            return cache[key];
        }
        console.log('calculating...');
        const res = fn.apply(this, [a, b, c]); // since it's not in the cash - calculate the result
        cache[key] = res; // now before we'll return the result - save it in the cache for next calls
        return res;
    };
})(f); // apply the memoization to the original function
memoized(1, 2, 3); // will print "calculating..." and return the result
memoized(1, 2, 3); // will print "in memory" and return the result

最新更新