Are functions in JavaScript tail-call optimized?

后端 未结 3 1892
慢半拍i
慢半拍i 2020-11-27 14:12

I have been trying to understand Tail call optimization in context of JavaScript and have written the below recursive and tail-recursive methods for facto

相关标签:
3条回答
  • 2020-11-27 14:31

    Update: As of January 1, 2020 Safari is the only browser that supports tail call optimization.

    The chromium team explicitly states that Tail Call Optimization is not under active development and can be tracked here.

    The implementation for Firefox can be tracked here

    Original Post

    Yes, ES2015 offers tail call optimization in strict mode. Dr. Axel Rauschmayer lays it out beautifully at the link below so I shall not repeat his words here.

    Note: ES 5 does not optimize tail calls.

    http://www.2ality.com/2015/06/tail-call-optimization.html

    0 讨论(0)
  • 2020-11-27 14:32

    As the other answers have said, not in practice. However, you can define a utility to help out.

    class Tco {
      constructor(func) {
        this.func = func;
      }
      execute() {
        let value = this;
        while (value instanceof Tco)
          value = value.func();
        return value;
      }
    }
    
    const tco = (f) => new Tco(f);
    
    function factorial (n) {
      const fact = (n, acc) => tco(() => {
        if (n < 2) {
          return acc;
        } else {
          return fact(n-1, n * acc);
        }
      });
    
      return fact(n, 1).execute();
    }
    
    console.log(factorial(2000000)); // Infinity
    

    As you can see, this allows you to write tail recursive functions with only a small difference in syntax, without running into a max call stack error.

    0 讨论(0)
  • 2020-11-27 14:44

    In theory yes. As the other answer states.

    In practice though, as of July 2017, No. Only Safari supports it.

    Javascript ES6 (ES2015) compatability: https://kangax.github.io/compat-table/es6/

    0 讨论(0)
提交回复
热议问题