Function makeAsyncTrampoline

  • Wraps an asynchronous recursive function inside an async trampoline executor.

    This helper transforms a recursive async function that returns a Trampoline (or Promise<Trampoline>) into a stack-safe async function that executes iteratively via the asyncTrampoline runner.

    Type Parameters

    • Args extends any[]

      The tuple type representing the argument list of the original function.

    • Result

      The final return type after all async trampoline steps are resolved.

    Parameters

    • fn: ((...args: Args) => Trampoline<Result> | Promise<Trampoline<Result>>)

      An async or sync function that performs a single step of computation and returns a Trampoline (either a final value or a deferred thunk).

        • (...args): Trampoline<Result> | Promise<Trampoline<Result>>
        • Parameters

          Returns Trampoline<Result> | Promise<Trampoline<Result>>

    Returns ((...args: Args) => Promise<Result>)

    An async function with the same arguments, but which automatically runs the trampoline process and resolves to the final result.

    // Example: Async factorial using trampoline
    const asyncFactorial = makeAsyncTrampoline(async function fact(
    n: number,
    acc: number = 1
    ): Promise<Trampoline<number>> {
    return n === 0
    ? acc
    : makeTrampolineThunk(() => fact(n - 1, acc * n));
    });

    asyncFactorial(100000).then(console.log); // Works without stack overflow