I used the following example to test tail call recursion with Babel and the es2016
preset:
'use strict';
try {
function r(n) {
if (n%5000===0)
console.log(`reached a depth of ${n}`);
r(n+1);
}
r(0);
} catch (e) {
if (!(e instanceof RangeError))
throw e;
else
console.log('stack blown');
}
My package.json
file is:
{
"name": "tail-call-optimization",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel es6 --out-dir es5 --source-maps",
"watch": "babel es6 --out-dir es5 --source-maps --watch",
"start": "node es5/app.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.6.5",
"babel-core": "^6.7.4",
"babel-loader": "^6.2.4",
"babel-polyfill": "^6.7.4",
"babel-preset-es2016": "^6.0.10",
"babel-runtime": "^6.6.1"
},
"dependencies": {
"babel-polyfill": "^6.7.4",
"source-map-support": "^0.4.0"
}
}
... and the .babelrc
is simply:
{
"presets": ["es2016"]
}
Running the above with:
npm run build && npm run start
... results in the following console output:
reached a depth of 0
reached a depth of 5000
reached a depth of 10000
reached a depth of 15000
stack blown
Indeed, looking at the transpiled file in the es5
directory, there's nothing to suggest that TCO has been implemented.
Am I missing something?
My node version is 4.3.2
.
None of the "official" Babel 6 plugins / presets currently implements TCO. babel-preset-es2016
is not an "official" preset. Unless TCO relies on parser support in Babylon (off the top of my head I wouldn't think so, but I'm not sure) then I suppose a userland plugin / preset could implement it, and perhaps does (but not that I know of). Here is the issue tracking eventual "official" re-implementation: T2614. If someone wants to PR that link into the Learn ES2015 docs @Marcus mentioned ping me here and I'll merge it.