Skip to content

memoize

memoize<A, B>(f, keyFn?): (a) => B

Defined in: Composition/memoize.ts:27

Creates a memoized version of a function that caches results. Subsequent calls with the same argument return the cached result.

By default, uses the argument directly as the cache key. For complex arguments, provide a custom keyFn to generate cache keys.

A

B

(a) => B

(a) => unknown

(a): B

A

B

// Basic usage
const expensive = memoize((n: number) => {
  console.log("Computing...");
  return n * 2;
});

expensive(5); // logs "Computing...", returns 10
expensive(5); // returns 10 (cached, no log)
expensive(3); // logs "Computing...", returns 6

// With custom key function for objects
const fetchUser = memoize(
  (opts: { id: string }) => fetch(`/users/${opts.id}`),
  opts => opts.id
);