Dev HelpersOpen library
← Back

Memoize a pure function

Memoize a pure function. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const memo = (f) => {
  const cache = new Map();
  return (x) => {
    if (!cache.has(x)) cache.set(x, f(x));
    return cache.get(x);
  };
};
const square = memo((n) => n * n);
console.log(square(8), square(8));

Sample output

64 64