es6-transpiler icon indicating copy to clipboard operation
es6-transpiler copied to clipboard

Support for tail call optimization

Open kobezzza opened this issue 10 years ago • 3 comments

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)

kobezzza avatar Jul 10 '14 07:07 kobezzza

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

nmn avatar Aug 01 '14 12:08 nmn

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);
}

kobezzza avatar Aug 01 '14 14:08 kobezzza

I can do it. Right after generator and modules

termi avatar Sep 05 '14 13:09 termi