Sunday, 11 June 2017

tail call optimization in javascript does not work

Ecmascript6 introduced tail call optimization(TCO),I wrote the next code

'use strict';
var isStrict = (function() { return !this; })();
function add5(a,total=0){
    if(a==1)return total+a;
    return add5(a-1,total+a);
}

add5(100000); 

and run it both in chrome(57.0.2987.133 (64-bit))

<script src="strict.js"></script>

and node(v8.1.0). they all print the result alike:

isStrict:true
/data/study/dashboards/api-demo/strict.js:4
function add5(a,total=0){
             ^

RangeError: Maximum call stack size exceeded
    at add5 (/data/study/dashboards/api-demo/strict.js:4:14)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)
    at add5 (/data/study/dashboards/api-demo/strict.js:6:12)

It seems the strict mode is enabled,but tail call optimization does not work,anybody can do me a favor and tell why?



via leo.liao

No comments:

Post a Comment