• Create a new Function that returns the memoized results of a Function. The key for the lookup cache is determined by the keyExtractor Function.

    An optional Map instance can be provided to be used as cache. This allows for example to prepopulate the cache, or to force recomputation of some values by removing their corresponding keys. If no instance is provided an empty Map will be created.

    Remarks

    The memoized function should be a pure function, because else side effects will only be executed once for each cached key.

    Example

    Memoize an expensive function

    const expensiveFunction = (a, b) => a + b;
    const keyExtractor = (a, b) => `${a}_${b}`;

    const memoizedFunction = memoize(expensiveFunction, keyExtractor);

    const result = memoizedFunction(2, 3);
    console.log(result); // 5

    Example

    Provide an initial cache restored from database

    const restoredCacheFromDatabase = new Map([["a", 1], ["ab", 2]]);
    const expensiveFunction = (s) => s.length;
    const keyExtractor = (s) => s;

    const memoizedFunction = memoize(expensiveFunction, keyExtractor, restoredCacheFromDatabase);

    const result = memoizedFunction("ab");
    console.log(result); // 2

    Example

    Clear cache after 5 seconds

    const cache = new Map();
    const expensiveFunction = (s) => s.length;
    const keyExtractor = (s) => s;

    const memoizedFunction = memoize(expensiveFunction, keyExtractor, cache);

    // ... fill the cache

    setTimeout(() => {
    cache.clear();
    }, 5000);

    Returns

    the memoized result

    Type Parameters

    • TArgs extends unknown[]

    • R

    Parameters

    • fn: ((...args: TArgs) => R)

      the Function to memoize

        • (...args: TArgs): R
        • Parameters

          • Rest ...args: TArgs

          Returns R

    • keyExtractor: ((...args: TArgs) => unknown)

      the Function to extract the key for the cache

        • (...args: TArgs): unknown
        • Parameters

          • Rest ...args: TArgs

          Returns unknown

    • cache: Map<unknown, R> = ...

      an optional, possibly prefilled Map instance to use as cache

    Returns ((...args: TArgs) => R)

      • (...args: TArgs): R
      • Parameters

        • Rest ...args: TArgs

        Returns R

Generated using TypeDoc