DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 87

The task is to implement a general memoization function.

The boilerplate code:

function memo(func, resolver) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Create a cache storage

const cache = new Map();
Enter fullscreen mode Exit fullscreen mode

Map allows any type of key, and is faster and safer than a plain object. A wrapped function is returned

return function(...args) {}
Enter fullscreen mode Exit fullscreen mode

To generate a cache key, the user determines how arguments map to a cache key.

return function (...args) {
    const key = resolver
      ? resolver(...args)
      : args.length === 1
        ? args[0]
        : JSON.stringify(args);
}
Enter fullscreen mode Exit fullscreen mode

Check if the cache exists. If it does, return the result immediately

if (cache.has(key)) {
  return cache.get(key);
}
Enter fullscreen mode Exit fullscreen mode

Call the original function once, and save the result for future calls

const result = func.apply(this, args);
cache.set(key, result);
Enter fullscreen mode Exit fullscreen mode

The final code

function memo(func, resolver) {
  // your code here
  const cache = new Map();

  return function(...args) {
    const key = resolver ? resolver(...args) : args.length === 1 ? args[0] : JSON.stringify(args);

    if(cache.has(key)) {
      return cache.get(key);
    }

    const result = func.apply(this, args);
    cache.set(key, result);
    return result;
  }
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)