LeetCode solutions

2731. Memoize

My accepted JavaScript solution to LeetCode problem 2731, Memoize, running in 238ms.

  • Difficulty: Medium
  • JavaScript
  • Runtime 238ms
  • Memory 95.7MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 238ms, memory 95.7MB, accepted 2025-12-29.

javascript
/**
 * @param {Function} fn
 * @return {Function}
 */
function memoize(fn) {
    const cache = new Map();
    
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) {
            return cache.get(key);
        }
        const result = fn(...args);
        cache.set(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 
 */

Source