JavaScript

Memoize Function

by @admin
10h ago
Apr 28, 2026
Public
Caches the result of a pure function keyed by its serialised arguments. On repeated calls with the same inputs the cached value is returned instantly, skipping expensive computation. Supports single and multi-argument functions via JSON key serialisation.
JavaScript
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;
  };
}

// Usage
const slowFib = (n) => (n <= 1 ? n : slowFib(n - 1) + slowFib(n - 2));
const fastFib = memoize(slowFib);
console.log(fastFib(40)); // instant after first call
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.