0

In preparation for fully adopted yield support, I've already find a seeming lack.

Is there a way to detect if a function is a generator in nodejs 0.11+?

dansch
  • 6,059
  • 4
  • 43
  • 59

1 Answers1

2

I don't like this way:

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

but it works.

Please respond if you have a better option.

dansch
  • 6,059
  • 4
  • 43
  • 59