Function memoize
- memoize<Fn, Key, Cache>(fn, options?): Fn
ExperimentalType Parameters
- Fn extends ((...args: never[]) => unknown)
The type of the function to memoize.
- Key = string
The type of the cache key.
- Cache extends MemoizationCache<Key, MemoizationCacheResult<ReturnType<Fn>>> = Map<Key, MemoizationCacheResult<ReturnType<Fn>>>
The type of the cache.
Parameters
- fn: Fn
The function to memoize
Optionaloptions: MemoizeOptions<Fn, Key, Cache>Options for memoization
Returns Fn
The memoized function.
Example: Basic usage
import { memoize } from "@std/cache";
import { assertEquals } from "@std/assert";
// fibonacci function, which is very slow for n > ~30 if not memoized
const fib = memoize((n: bigint): bigint => {
return n <= 2n ? 1n : fib(n - 1n) + fib(n - 2n);
});
assertEquals(fib(100n), 354224848179261915075n);[!NOTE]
- By default, memoization is on the basis of all arguments passed to the
function, with equality determined by reference. This means that, for
example, passing a memoized function as
arr.map(func)will not use the cached results, as the index is implicitly passed as an argument. To avoid this, you can pass a customgetKeyoption or use the memoized function inside an anonymous callback likearr.map((x) => func(x)).
- Fn extends ((...args: never[]) => unknown)
Cache the results of a function based on its arguments.
UNSTABLE: New API, yet to be vetted.