考虑一个正常的递归函数
function sum(x, y) {if (y > 0) {return sum (x + 1, y - 1);} else {return x;}
}
sum(1, 100000000);
超出调用栈的最大次数…
下面使用尾递归优化实现:
function tco(f) {var value ;var active = false;var accumulated = [];return function accumulator() {accumulated.push(arguments);if (!active) {active = true;while (accumulated.length) {value = f.apply(this, accumulated.shift());}active = false;return value;}};
}var sum = tco(function (x, y) {if (y > 0) {return sum(x + 1, y -1)}else {return x}
});
console.log(sum(1, 1000000));
参考《ES6标准入门》(第3版) P130~P131