0

I have a slow function

function f(a, b, c) {
}

I call this function with same arguments sometimes, it will return the same result. I want to cache this function call with arguments, so second call with same arguments returns from cache.

I tried this but it doesn't work.

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);
  };
}             
eguneys
  • 6,028
  • 7
  • 31
  • 63

1 Answers1

1

In order to use a cache we need to map the arguments to the result. Since you have multiple parameters, you'll need to generate a unique key for these parameters. For example, in case you have 3 parameters: a, b, c - you can create a key: \${a}-${b}-${c}`` (this is just an example, the only important thing is that this key will be unique!).

Demo (see code-comments for additional explanations):

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
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • 1
    You should use `if (cache.hasOwnProperty(key))` instead of `if (cache[key])`. Your current code never memoizes falsely values (false, undefined, null, 0, "", etc). – Nate Aug 05 '19 at 03:31