Skip to content

memoize

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

Defined in: Composition/memoize.ts:34

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 keyBy to generate cache keys.

A

B

(a) => B

(a) => unknown

Maps an argument to the value used as its cache key. Defaults to the argument itself.

number

Maximum number of entries to store before evicting the least recently used entry. Fractional values are floored; 0 disables caching; Infinity means unbounded. Negative or NaN values disable caching.

(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 format = memoize(
  (item: { price: number; currency: string }) => `${item.currency}${item.price.toFixed(2)}`,
  { keyBy: (item) => `${item.currency}:${item.price}` }
);
// With bounded cache size (LRU eviction)
const bounded = memoize(
  (n: number) => n * 2,
  { maxSize: 100 }
);