termi / es6-transpiler

Tomorrow's JavaScript syntax today
Other
216 stars 18 forks source link

Support for tail call optimization #40

Open kobezzza opened 10 years ago

kobezzza commented 10 years ago

http://www.2ality.com/2014/04/call-stack-size.html ECMAScript 6 will have tail call optimization: If a function call is the last action in a function, it is handled via a “jump”, not via a “subroutine call”. That means that, if you slightly rewrote computeMaxCallStackSize(), it would run forever under ECMAScript 6 (in strict mode)

nmn commented 10 years ago

This is not possible as a transpiler and is something that needs to be added at the javascript engine level.

kobezzza commented 10 years ago

It's possible. Absolutely any recursion can be written in the form Cycle. Tail recursion is optimized very simple, because they don't need the call stack.

http://en.wikipedia.org/wiki/Tail_call

For example LispyScript supports it.

// Tail call recursion

function fac_times(n, acc) {
    return (n == 0) ? acc : fac_times(n - 1, acc * n);
}

function factorial(n) {
    return fac_times(n, 1);
}

// After optimization

function fac_times(n, acc) {
    while (true) {
        if (n == 0) {
            return acc;
        }

        var old_n = n,
            old_acc = acc;

        n = old_n - 1;
        acc = old_acc * old_n;
    }
}

function factorial(n) {
    return fac_times(n, 1);
}
termi commented 10 years ago

I can do it. Right after generator and modules