eguneys
eguneys

Reputation: 6396

How to memoize function so same arguments returns from cache

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);
  };
}             

Upvotes: -1

Views: 1237

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

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

Upvotes: 1

Related Questions