npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

js-tail-recursion-opt-plugin

v1.0.0

Published

A modern TypeScript/JavaScript compiler plugin for automatic tail call optimization

Readme

js-tail-recursion-opt-plugin

npm version Test codecov License: MIT

A modern TypeScript/JavaScript compiler plugin that automatically optimizes tail-recursive functions into efficient loops at compile time.

Production Ready • 🧪 100% Test Coverage • 🚀 Zero Runtime Overhead

🚀 Features

  • Automatic Detection: Scans your code for tail-recursive patterns
  • Loop Transformation: Converts tail calls to while loops for better performance
  • Stack Overflow Prevention: Eliminates stack overflow issues with deep recursion
  • TypeScript Support: Full TypeScript compatibility
  • Zero Runtime Overhead: Optimization happens at compile time
  • Configurable: Control which functions to optimize with annotations
  • Comprehensive Testing: Extensive test suite ensures correctness

📦 Installation

npm install --save-dev js-tail-recursion-opt-plugin
# or
yarn add -D js-tail-recursion-opt-plugin

🔧 Usage

With Babel

Add the plugin to your Babel configuration:

.babelrc

{
  "plugins": ["js-tail-recursion-opt-plugin"]
}

babel.config.js

module.exports = {
  plugins: ['js-tail-recursion-opt-plugin']
};

With Options

{
  "plugins": [
    ["js-tail-recursion-opt-plugin", {
      "debug": false,
      "onlyAnnotated": false,
      "annotationTag": "@tail-recursion"
    }]
  ]
}

📖 Examples

Basic Tail Recursion

Before:

function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc);
}

factorial(10000); // ❌ RangeError: Maximum call stack size exceeded

After optimization:

function factorial(n, acc = 1) {
  while (true) {
    if (n <= 1) return acc;
    
    let _n_ = n - 1;
    let _acc_ = n * acc;
    n = _n_;
    acc = _acc_;
    continue;
  }
}

factorial(10000); // ✅ Works! Returns Infinity (BigInt for exact result)

Real-World Examples

1. Array Sum

function sum(arr, index = 0, acc = 0) {
  if (index >= arr.length) return acc;
  return sum(arr, index + 1, acc + arr[index]);
}

// Before: Stack overflow at ~10,000 items
// After: Handles millions of items
sum(Array(1000000).fill(1)); // ✅ Returns 1000000

2. Fibonacci Sequence

function fib(n, a = 0, b = 1) {
  if (n === 0) return a;
  return fib(n - 1, b, a + b);
}

// Before: Stack overflow at ~10,000
// After: Works for any n
fib(10000); // ✅ Returns BigInt result

3. String Reverse

function reverse(str, acc = '') {
  if (str.length === 0) return acc;
  return reverse(str.slice(1), str[0] + acc);
}

reverse('a'.repeat(100000)); // ✅ Works!

4. Deep Object Traversal

function flatten(obj, prefix = '', acc = {}) {
  if (typeof obj !== 'object') {
    acc[prefix] = obj;
    return acc;
  }
  
  for (const key in obj) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    flatten(obj[key], newKey, acc);
  }
  
  return acc;
}

// Handles deeply nested objects without stack overflow

Arrow Functions

// Also works with arrow functions!
const sum = (n, acc = 0) => {
  if (n === 0) return acc;
  return sum(n - 1, acc + n);
};

Conditional Tail Calls

// Ternary operators
const countdown = (n, acc = []) => 
  n === 0 ? acc : countdown(n - 1, [...acc, n]);

// Multiple conditions
function search(arr, target, index = 0) {
  if (index >= arr.length) return -1;
  if (arr[index] === target) return index;
  return search(arr, target, index + 1);
}

⚙️ Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | debug | boolean | false | Enable debug logging during compilation | | onlyAnnotated | boolean | false | Only optimize functions with annotation comments | | annotationTag | string | "@tail-recursion" | Custom annotation tag to identify functions for optimization |

Using Annotations

When onlyAnnotated is enabled, only functions with the specified annotation will be optimized:

/** @tail-recursion */
function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc);
}

// This won't be optimized
function notOptimized(n) {
  return n > 0 ? n + notOptimized(n - 1) : 0;
}

🧪 What Gets Optimized?

✅ Supported Patterns

  • Simple tail recursion
  • Tail calls in conditional expressions (ternary)
  • Tail calls in if/else branches
  • Tail calls in logical expressions (&&, ||)
  • Arrow functions with tail recursion
  • Function expressions assigned to variables

❌ Not Optimized

  • Non-tail recursive calls (e.g., return n * factorial(n-1))
  • Mutual recursion
  • Recursion with try/catch blocks
  • Functions with both tail and non-tail recursive calls

🎯 Performance Benefits

Tail call optimization can dramatically improve performance and prevent stack overflow errors:

// Without optimization: Stack overflow at ~10,000 iterations
// With optimization: Can handle millions of iterations

function sum(n, acc = 0) {
  if (n === 0) return acc;
  return sum(n - 1, acc + n);
}

sum(1000000); // ✅ Works with optimization

📚 Documentation

🎓 Best Practices

Converting Non-Tail Recursion to Tail Recursion

Before (Non-Tail):

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);  // ❌ Not in tail position
}

After (Tail Recursive):

function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc);  // ✅ Tail position!
}

Using Accumulator Pattern

The accumulator pattern is key to tail recursion:

// Sum with accumulator
function sum(arr, index = 0, acc = 0) {
  if (index >= arr.length) return acc;
  return sum(arr, index + 1, acc + arr[index]);
}

// Filter with accumulator
function filter(arr, pred, index = 0, acc = []) {
  if (index >= arr.length) return acc;
  if (pred(arr[index])) {
    return filter(arr, pred, index + 1, [...acc, arr[index]]);
  }
  return filter(arr, pred, index + 1, acc);
}

🛠️ Development

# Install dependencies
npm install

# Build the plugin
npm run build

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run benchmarks
npm run benchmark

🧪 Testing

# Run all tests
npm test

# With coverage
npm test -- --coverage

# Specific test file
npm test -- basic.test.ts

🧩 How It Works

  1. Detection Phase: The plugin scans the AST for recursive function calls
  2. Validation: Ensures all recursive calls are in tail position
  3. Transformation: Converts the function body into a while(true) loop
  4. Variable Management: Uses temporary variables to safely update parameters

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT © [Your Name]

🔗 Links

📚 Related Projects


Made with ❤️ by the JavaScript community