Skip to main content
Back to problems
#2630
Hard JavaScript

Memoize ii

38.4% acceptance
Mar 2, 2026
133
46
Given a function fn, return a memoized version of that function. A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value. fn can be any function and there are no constraints on what type of values it accepts. Inputs are considered identical if they are === to each other.

Solution

TypeScript
Time O(n)
Space O(n)
LeetCode
solution.ts
type Fn = (...params: any) => any;

function memoize(fn: Fn): Fn {
  const cache = new Map<any, any>();

  function getOrCreate(map: Map<any, any>, key: any): Map<any, any> {
  if (!map.has(key)) map.set(key, new Map());
  return map.get(key)!;
  }

  return function (...args: any[]): any {
  let node: Map<any, any> = cache;
  for (const arg of args) {
    node = getOrCreate(node, arg);
  }
  const RESULT_KEY = Symbol.for("__result__");
  if (node.has(RESULT_KEY)) return node.get(RESULT_KEY);
  const result = fn(...args);
  node.set(RESULT_KEY, result);
  return result;
  };
}

/**
 * let callCount = 0;
 * const memoizedFn = memoize(function (a, b) {
 *   callCount += 1;
 *   return a + b;
 * })
 * memoizedFn(2, 3) // 5
 * memoizedFn(2, 3) // 5
 * console.log(callCount) // 1
 */