• Returns memoized version of the parameter function fn. The memoized function will return cached value as long as the arguments of the call have the same tracked values as the last time.

    Memoized function has two cache levels:

    • A WeakMap by first object parameter
    • Global cache that only holds the last execution result.

    See

    IMemoizeOptions for details on available options.

    Returns

    memoized function.

    Example

    With two parameters:

    import { memoize } from '@indutny/sneequals';

    const fn = memoize((a, b) => ({ result: a.value + b.value }));

    // Prints `{ result: 3 }`
    const answer = fn({ value: 1 }, { value: 2 });
    console.log(answer);

    const cachedAnswer = fn({ value: 1 }, { value: 2 });

    // Even though the input objects are different the `cachedResult` is the
    // same since the tracked properties didn't change.
    // Prints `true`.
    console.log(answer === cachedAnswer);

    Example

    With react-redux and an id lookup. (Taken from proxy-memoize.)

    import { useCallback } from 'react';
    import { useSelector } from 'react-redux';
    import { memoize } from '@indutny/sneequals';

    const Component = ({ id }) => {
    const { score, title } = useSelector(useCallback(memoize(state => ({
    score: getScore(state),
    title: state.titles[id],
    })), [id]));
    return <div>{score.score} {score.createdAt} {title}</div>;
    };

    Type Parameters

    • Params extends readonly unknown[]

    • Result

    Parameters

    • fn: ((...params: Params) => Result)

      function to be memoized

        • (...params: Params): Result
        • Parameters

          • Rest ...params: Params

          Returns Result

    • Optional options: IMemoizeOptions<Params>

      an optional options object

    Returns ((...params: Params) => Result)

      • (...params: Params): Result
      • Parameters

        • Rest ...params: Params

        Returns Result

Generated using TypeDoc