Skip to content

memoize

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

Defined in: Composition/memoize.ts:32

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

number

Maximum number of entries to store in the cache before evicting the least recently used (LRU) entry.

(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}`),
  { key: (opts) => opts.id }
);
// With bounded cache size (LRU eviction)
const bounded = memoize(
  (n: number) => n * 2,
  { maxSize: 100 }
);