Skip to content

Infinite recursion in JS without stack overflow errors, based on magic πŸŽ©βœ¨πŸ‡

License

Notifications You must be signed in to change notification settings

crubier/infinistack

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Infinistack πŸŽ©βœ¨πŸ‡

Infinite recursion in JS without stack overflow errors!

Based on magic, memoization, abuse of exceptions and the work of @razimantv.

If you need this package to make your code work, then my advice would be to rethink your code structure. This library works, but is not efficient or safe. Instead of using this, unroll your recursion into iterative algorithms, you will thank me later.

By @crubier

Install

npm install infinistack

Usage

Here is a classical, "dumb" factorial implementation:

const factorial = N => {
  if (N == 0) {
    return 1;
  }
  return N * factorial(N - 1);
};

// Don't do this, it will crash:
console.log(factorial(180000));

This can be transformed with infinistack in order to emancipate from stack overflow errors:

import infinistack from "infinistack";

const factorial = infinistack(N => {
  if (N == 0) {
    return 1;
  }
  return N * factorial(N - 1);
});

// This works now!
console.log(factorial(180000));

For more info, see the tests

Amazing. Thanks to @razimantv for the original idea in python

Caveats

Not yet tested on:

  • Async functions
  • Complex recursion schemes
  • Function with non-stringifiable arguments (higher order functions for example)

About

Infinite recursion in JS without stack overflow errors, based on magic πŸŽ©βœ¨πŸ‡

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published