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
x
15
15
1
function *range(start,end){
2
3
while(start < end){
4
yield start;
5
start++
6
}
7
}
8
9
let iterator = range(1,10);
10
11
// so I can do something like this.
12
while(iterator.hasNext()){
13
console.log(iterator.next().value);
14
}
15
Advertisement
Answer
The simple non-for…of
way to loop an iterator is
JavaScript
1
4
1
for (let iterator = range(1, 10), r; !(r = iterator.next()).done; ) {
2
console.log(r.value);
3
}
4
If you really want to use hasNext
, you can do that as well, but it’s a bit weird:
JavaScript
1
10
10
1
const iterator = range(1, 10);
2
iterator.hasNext = function hasNext() {
3
const r = this.next();
4
this.current = r.value;
5
return !r.done;
6
};
7
while (iterator.hasNext()) {
8
console.log(iterator.current);
9
}
10