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?
TJ Holowaychuk's
co
library has the best function for checking whether something is a generator function. Here is the source code:Reference: https://github.com/tj/co/blob/717b043371ba057cb7a4a2a4e47120d598116ed7/index.js#L221
As @Erik Arvidsson stated, there is no standard-way to check if a function is a generator function. But you can, for sure, just check for the interface, a generator function fulfills:
Thats's it.
A difficulty not addressed on here yet is that if you use the
bind
method on the generator function, it changes the name its prototype from 'GeneratorFunction' to 'Function'.There's no neutral
Reflect.bind
method, but you can get around this by resetting the prototype of the bound operation to that of the original operation.For example:
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.