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().

function *range(start,end){

    while(start < end){
        yield start; 
        start++
    }
}

let iterator = range(1,10); 

// so I can do something like this. 
while(iterator.hasNext()){
   console.log(iterator.next().value); 
}

Answer

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

for (let iterator = range(1, 10), r; !(r = iterator.next()).done; ) {
    console.log(r.value);
}

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

const iterator = range(1, 10);
iterator.hasNext = function hasNext() {
    const r = this.next();
    this.current = r.value;
    return !r.done;
};
while (iterator.hasNext()) {
    console.log(iterator.current);
}


Source: stackoverflow