Skip to content
Advertisement

hasNext() for ES6 Generator

How would I implement hasNext() method for a generator. I have tried many options like adding the generator as a return statement and yielding from the closure. Getting the first value printing it and then using the while etc, but none of them actually worked.

I know I can use for of or while like How to loop the JavaScript iterator that comes from generator? but still wondering if I can add hasNext().

JavaScript

Advertisement

Answer

The simple non-for…of way to loop an iterator is

JavaScript

If you really want to use hasNext, you can do that as well, but it’s a bit weird:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement