Memoize

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Memoization

JS · Common Patterns
syntax
function memoize(fn) { ... }
example
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.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

const expensiveCalc = memoize((n) => {
  console.log("Computing...");
  return n ** 2 + Math.sqrt(n);
});

console.log(expensiveCalc(100)); // "Computing..." then 10010
console.log(expensiveCalc(100)); // 10010 (cached, no log)

Note Caches results for repeated calls with the same arguments. Use JSON.stringify for simple keys. For complex args, consider a WeakMap-based approach.

PYPython

functools Module

PY · Common Standard Library
syntax
from functools import lru_cache, partial, reduce
example
from functools import lru_cache, partial

@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(30))
print(fibonacci.cache_info())

# partial: pre-fill arguments
def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
print(square(7))
output
832040
CacheInfo(hits=28, misses=31, maxsize=128, currsize=31)
49

Note lru_cache requires hashable arguments. For unhashable args, consider cachetools or a manual cache. partial is great for adapting callback signatures.