Function thunkify

  • 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[]) => unknown

    Parameters

    • fn: T

      The function to thunkify

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

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

    Higher order

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

    const thunk = thunkify(add);

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