How to tell function and generator function apart?

Claude Pache claude.pache at gmail.com
Tue Mar 3 16:57:54 UTC 2015


Here is how to get your answer:

	g.toString().startsWith("function*")

Since being a generator function (in contrast with being a function that may return an iterator) is a question of implementation rather of behaviour, I think that peeking at the source code using `.toString()` is the right way to do it.

—Claude

> Le 3 mars 2015 à 17:41, Guilherme Souza <19gui94 at gmail.com> a écrit :
> 
> Hi all,
> 
> I was wondering how one could check if a given function is a generator function, is a cross-realm way:
> 
> ```
> let f = function(){}
> let g = function*(){}
> 
> typeof f === typeof g // 'function'
> 
> f instanceof Function // true, but only in the same Realm
> g instanceof Function // true, but again only in the same Realm
> 
> let GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
> f instanceof GeneratorFunction // false
> g instanceof GeneratorFunction // true, but only in the same Realm
> 
> // This works, but relies on Function.prototype being a function itself.
> typeof Object.getPrototypeOf(f) // 'function'
> typeof Object.getPrototypeOf(g) // 'object'
> ```
> 
> So what is the recommended way to do this type of check?
> Would something like `Array.isArray` for generator functions be helpful?
> 
> Regards,
> Gui
> 
> 
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150303/f07d4a58/attachment.html>


More information about the es-discuss mailing list