Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
}
like image 555
Yasin Yaqoobi Avatar asked Sep 02 '16 15:09

Yasin Yaqoobi


1 Answers

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);
}
like image 64
Bergi Avatar answered Oct 01 '22 03:10

Bergi