Coding Challenge Practice - Question 87

Published: (December 26, 2025 at 08:16 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem

Implement a general memoization function.

Solution Overview

  • Use a Map as cache storage.
  • Generate a cache key with an optional resolver; if none is provided, use the single argument directly or JSON.stringify the arguments array.
  • Return the cached result when available; otherwise call the original function, store its result, and return it.

Implementation

function memo(func, resolver) {
  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;
  };
}
Back to Blog

Related posts

Read more »