A type-safe way to emulate tail-call optimization with trampolines
npm install trampoline-ts


A type-safe way to emulate tail-call optimization with trampolines
``sh`
npm i trampoline-tsor
yarn add trampoline-ts
Requires a TypeScript version >= 3.0
`ts
import { trampoline, ThunkOrValue } from 'trampoline-ts';
const factorial = trampoline((n: number, acc: number = 1): ThunkOrValue
return n
// Note: calling factorial.cont instead of factorial directly
? factorial.cont(n - 1, acc * n)
: acc;
});
factorial(32768); // No stack overflow
`
##### trampoline
Takes a Tail Recursive Form function that returns a ThunkOrValue andTrampoline
converts it to a tail-call optimized function. The returned function will have the exact same type signature as the passedThunkOrValue
function except for one change, the return type will not contain, it will just be T.
It's important that fn wraps the return type in ThunkOrValue. If this isany
omitted, TypeScript will not be able to infer the type of the returned
function and will default to .
Also note that to continue function recursion Trampoline should.cont()
be called, and not the function directly. has the same type
signature as the passed function, so there's no way to call it incorrectly.
##### Trampoline
A function that represents a tail-call optimized function.
##### Trampoline
Function used to safely continue recursion. It captures F`'s argument and
return types and thus has the same type signature.