Cache function

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.

Frequently asked questions

How does JavaScript handle cache function?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Memoization" snippet in JavaScript uses `function memoize(fn) { ... }`.
Which code does the JavaScript example use?
The "Memoization" snippet uses `function memoize(fn) { ... }`, from the Common Patterns section of the JavaScript cheat sheet.
Which stacks cover "cache function" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Memoization": Caches results for repeated calls with the same arguments. Use JSON.stringify for simple keys. For complex args, consider a WeakMap-based approach.