🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
DemoInstallSign in
Socket

trampoline-ts

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

trampoline-ts

A type-safe way to emulate tail-call optimization with trampolines

1.1.0
latest
Source
npm
Version published
Weekly downloads
7.3K
9.47%
Maintainers
1
Weekly downloads
 
Created
Source

Trampoline TS

Build Status Coverage Status npm version

A type-safe way to emulate tail-call optimization with trampolines

Install

npm i trampoline-ts
# or
yarn add trampoline-ts

TypeScript Compatibility

Requires a TypeScript version >= 3.0

Usage

import { trampoline, ThunkOrValue } from 'trampoline-ts';

const factorial = trampoline((n: number, acc: number = 1): ThunkOrValue<number> => {
  return n
    // Note: calling factorial.cont instead of factorial directly
    ? factorial.cont(n - 1, acc * n)
    : acc;
});

factorial(32768); // No stack overflow

API

trampoline<F extends ((...args: any[]) => ThunkOrValue<any>)>(fn: F): Trampoline<F>

Takes a Tail Recursive Form function that returns a ThunkOrValue<T> and converts it to a tail-call optimized function. The returned function Trampoline<F> will have the exact same type signature as the passed function except for one change, the return type will not contain ThunkOrValue<T>, it will just be T.

It's important that fn wraps the return type in ThunkOrValue. If this is omitted, TypeScript will not be able to infer the type of the returned function and will default to any.

Also note that to continue function recursion Trampoline<F>.cont() should be called, and not the function directly. .cont() has the same type signature as the passed function, so there's no way to call it incorrectly.

Trampoline<F extends ((...args: any[]) => ThunkOrValue<any>>

A function that represents a tail-call optimized function.

Trampoline<F>.cont(...args: ArgumentTypes<F>): Thunk<ReturnType<F>>

Function used to safely continue recursion. It captures F's argument and return types and thus has the same type signature.

Keywords

trampoline

FAQs

Package last updated on 26 Apr 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts