Function thunkify

  • Category

    Create a new function that calls the provided fn with the given arguments. After the first call the return value will be cached and returned again, meaning you technically only need to pass the arguments the first time.

    Time complexity: O(1)

    Space complexity: O(1)

    Type Parameters

    • T extends ((...args) => unknown)

    Parameters

    • fn: T

      The function to thunkify

    Returns ((...parameters) => ReturnType<T>)

    A function that returns whatever the first call of fn returns for the given arguments

    Higher order

      • (...parameters): ReturnType<T>
      • Parameters

        • Rest ...parameters: Parameters<T>

        Returns ReturnType<T>

    Example

    function add(a, b) {
    return a + b;
    }

    const thunk = thunkify(add);

    thunk(1, 2); // 3
    thunk(3, 4); // 3