check if function is a generator

后端 未结 12 1390
-上瘾入骨i
-上瘾入骨i 2020-11-29 06:03

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 ===

相关标签:
12条回答
  • 2020-11-29 06:03

    TJ Holowaychuk's co library has the best function for checking whether something is a generator function. Here is the source code:

    function isGeneratorFunction(obj) {
       var constructor = obj.constructor;
       if (!constructor) return false;
       if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
       return isGenerator(constructor.prototype);
    }
    

    Reference: https://github.com/tj/co/blob/717b043371ba057cb7a4a2a4e47120d598116ed7/index.js#L221

    0 讨论(0)
  • 2020-11-29 06:04

    Mozilla javascript documentation describes Function.prototype.isGenerator method MDN API. Nodejs does not seem to implement it. However if you are willing to limit your code to defining generators with function* only (no returning iterable objects) you can augment it by adding it yourself with a forward compatibility check:

    if (typeof Function.prototype.isGenerator == 'undefined') {
        Function.prototype.isGenerator = function() {
            return /^function\s*\*/.test(this.toString());
        }
    }
    
    0 讨论(0)
  • 2020-11-29 06:04

    I checked how koa does it and they use this library: https://github.com/ljharb/is-generator-function.

    You can use it like this

    const isGeneratorFunction = require('is-generator-function');
    if(isGeneratorFunction(f)) {
        ...
    }
    
    0 讨论(0)
  • 2020-11-29 06:12

    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';
    }
    
    0 讨论(0)
  • 2020-11-29 06:12

    I'm using this:

    var sampleGenerator = function*() {};
    
    function isGenerator(arg) {
        return arg.constructor === sampleGenerator.constructor;
    }
    exports.isGenerator = isGenerator;
    
    function isGeneratorIterator(arg) {
        return arg.constructor === sampleGenerator.prototype.constructor;
    }
    exports.isGeneratorIterator = isGeneratorIterator;
    
    0 讨论(0)
  • 2020-11-29 06:14
    function isGenerator(target) {
      return target[Symbol.toStringTag] === 'GeneratorFunction';
    }
    

    or

    function isGenerator(target) {
      return Object.prototype.toString.call(target) === '[object GeneratorFunction]';
    }
    
    0 讨论(0)
提交回复
热议问题