check if function is a generator

后端 未结 12 1415
-上瘾入骨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:21

    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:

    function* fibonacci(prevPrev, prev) {
    
      while (true) {
    
        let next = prevPrev + prev;
    
        yield next;
    
        prevPrev = prev;
        prev = next;
      }
    }
    
    // fetch get an instance
    let fibonacciGenerator = fibonacci(2, 3)
    
    // check the interface
    if (typeof fibonacciGenerator[Symbol.iterator] == 'function' && 
        typeof fibonacciGenerator['next'] == 'function' &&
        typeof fibonacciGenerator['throw'] == 'function') {
    
      // it's safe to assume the function is a generator function or a shim that behaves like a generator function
    
      let nextValue = fibonacciGenerator.next().value; // 5
    }
    

    Thats's it.

提交回复
热议问题