【问题标题】:Detect if a function is a generator [duplicate]检测函数是否是生成器[重复]
【发布时间】:2014-04-17 18:41:33
【问题描述】:

在为完全采用的收益支持做准备时,我已经发现了一个看似不足的地方。

在 nodejs 0.11+ 中有没有办法检测一个函数是否是一个生成器?

【问题讨论】:

    标签: node.js generator yield


    【解决方案1】:

    我不喜欢这种方式:

    var
      // pull out regex for speed
      genRegex = /^function[\s]*\*/,
    
      detectGenerator = function(mth){
        return (typeof mth == 'function') &&
        genRegex.test(mth.toString());
      };
    
    
    function * foo (){};
    function *bar (){};
    function* baz (){};
    function*qux (){};
    function non (){};
    
    console.log(detectGenerator(function (){}), detectGenerator(function(){})) // false, false
    console.log(detectGenerator(function  *(){}), detectGenerator(function*  (){})) // true, true
    console.log(detectGenerator(function * (){}), detectGenerator(function*(){})) // true, true
    console.log(detectGenerator(foo), detectGenerator(bar)) // true, true
    console.log(detectGenerator(baz), detectGenerator(qux)) // true, true
    console.log(detectGenerator(non)) // false
    

    但它有效。

    如果您有更好的选择,请回复。

    【讨论】:

    • 您必须使您的正则表达式适应命名函数。
    猜你喜欢
    • 2013-05-21
    • 2016-03-10
    • 2019-05-23
    • 2018-11-08
    • 2016-06-30
    • 2020-11-22
    • 1970-01-01
    • 2012-02-22
    • 2012-10-14
    相关资源
    最近更新 更多