You can use the tco module to emulate tail call optimization even on the old node. I will add an example using your code for this answer in a minute.
By changing the code a bit, you can even run 10 million recursion levels:
var tco = require('tco'); var countTo = tco(function (n, acc) { if (n === 0) { return [null, acc]; } return [countTo, [n - 1, acc + n]]; }); console.log(countTo(10000000, 0));
You can use Sweet macros to make them look bigger:
var countTo = tco(function (n, acc) { if (n === 0) { ret acc; } ret countTo(n - 1, acc + n); }); console.log(countTo(10000000, 0));
Which basically changes return to ret , but currently my macros that I used before do not seem to work with the current version of Sweet.js - I have to examine it when I have time.
Disclaimer: I am the author of this module.
source share