Function memoize

  • Experimental

    Cache the results of a function based on its arguments.

    UNSTABLE: New API, yet to be vetted.

    Type Parameters

    Parameters

    Returns Fn

    The memoized function.

    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 custom getKey option or use the memoized function inside an anonymous callback like arr.map((x) => func(x)).