memoize
import { memoize } from "jsr:@ende/cache";function ยท experimental
function memoize<Fn extends (...args: never[]) => unknown, Key = string, Cache extends MemoizationCache<Key, MemoizationCacheResult<ReturnType<Fn>>> = Map<Key, MemoizationCacheResult<ReturnType<Fn>>>>(fn: Fn, options?: MemoizeOptions<Fn, Key, Cache>): Fn & { cache: Cache }Cache the results of a function based on its arguments.
fn: FnThe function to memoize
options?: MemoizeOptions<Fn, Key, Cache>Options for memoization
Returns
The memoized function, with a cache property exposing the
underlying cache for inspection or manual invalidation.
Example: Basic usage
import { memoize } from "@ende/cache";
import { assertEquals } from "@ende/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)).