javascript - `es2016` 预设的 Babel 是否实现了尾调用优化?

标签 javascript babeljs tail-recursion

我使用以下示例来测试 Babel 和 es2016 预设的尾调用递归:

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

我的 package.json 文件是:

{
    "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"
    }
}

... 而 .babelrc 就是:

{
    "presets": ["es2016"]
}

运行上面的代码:

npm run build && npm run start

...导致以下控制台输出:

reached a depth of 0
reached a depth of 5000
reached a depth of 10000
reached a depth of 15000
stack blown

确实,查看 es5 目录中的转译文件,没有任何迹象表明 TCO 已经实现。

我错过了什么吗?

我的节点版本是4.3.2

最佳答案

查看:https://babeljs.io/docs/learn-es2015/一个是:

Temporarily Removed in Babel 6

Only explicit self referencing tail recursion was supported due to the complexity and performance impact of supporting tail calls globally. Removed due to other bugs and will be re-implemented.

所以我猜它目前还没有实现。

关于javascript - `es2016` 预设的 Babel 是否实现了尾调用优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36445393/

相关文章:

javascript - 如何在 react 中设置类属性的值

c# - 像实时新闻提要ajax刷新一样实现facebook?

javascript - 如何在 Windows PhpStorm 中安装和使用 Babel 和 watchers?

javascript - 在浏览器中访问 webpack 捆绑库

recursion - 我如何表达阶乘 n!使用 F# 函数,递归还是其他方式?

python - 如何强制一个函数在调用另一个函数后退出?

javascript - 如何使用 Protractor 检查类名的变化

javascript - jQuery 通过属性值获取/选择元素

reactjs - 我应该通过 .babelrc 还是 WebPack 配置 Babel?

function - 如何将此函数转换为使用尾调用