Skip to content

memoize

Returns a memoized version of the function that caches results.

Cache keys are derived via JSON.stringify; undefined arguments are correctly distinguished from null. Arguments that are not JSON-serializable (functions, symbols, class instances, circular references) produce a null-equivalent key and are not supported.

Available since v1.9.0

import { memoize } from '@helpers4/function';
memoize<A extends unknown[], R>(func: function, options?: MemoizeOptions): function
ParameterTypeDescription
funcfunctionThe function to memoize
optionsMemoizeOptionsOptional settings (e.g. maxSize to cap memory usage) (optional)

function — The memoized function

The underlying function is only called once for the same arguments.

let calls = 0;
const expensive = memoize((n: number) => { calls++; return n * 2; });
expensive(5); // => 10 (computed)
expensive(5); // => 10 (cached)

Options for memoize.

interface MemoizeOptions {
  maxSize?: number;
}

View source on GitHub