Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if function is a generator

I played with generators in Nodejs v0.11.2 and I'm wondering how I can check that argument to my function is generator function.

I found this way typeof f === 'function' && Object.getPrototypeOf(f) !== Object.getPrototypeOf(Function) but I'm not sure if this is good (and working in future) way.

What is your opinion about this issue?

like image 331
Dima Vidmich Avatar asked May 25 '13 23:05

Dima Vidmich


2 Answers

We talked about this in the TC39 face-to-face meetings and it is deliberate that we don't expose a way to detect whether a function is a generator or not. The reason is that any function can return an iterable object so it does not matter if it is a function or a generator function.

var iterator = Symbol.iterator;  function notAGenerator() {   var  count = 0;   return {     [iterator]: function() {       return this;     },     next: function() {       return {value: count++, done: false};     }   } }  function* aGenerator() {   var count = 0;   while (true) {     yield count++;   } } 

These two behave identical (minus .throw() but that can be added too)

like image 78
Erik Arvidsson Avatar answered Oct 16 '22 18:10

Erik Arvidsson


In the latest version of nodejs (I verified with v0.11.12) you can check if the constructor name is equal to GeneratorFunction. I don't know what version this came out in but it works.

function isGenerator(fn) {     return fn.constructor.name === 'GeneratorFunction'; } 
like image 28
smitt04 Avatar answered Oct 16 '22 19:10

smitt04