I am a beginner reading the chapter Iterators from the book
JavaScript: The Definitive Guide
I am not able to understand the next() method in the below example from book which is about Creating iterable-based alternative to the filter() method of JavaScript arrays.
// Return an iterable object that filters the specified iterable,
// iterating only those elements for which the predicate returns true
function filter(iterable, predicate) {
let iterator = iterable[Symbol.iterator]();
return { // This object is both iterator and iterable
[Symbol.iterator]() {
return this;
},
next() {
for(;;) {
let v = iterator.next();
if(v.done || predicate(v.value)) {
return v;
}
}
}
};
}
Let's test this function with an array.
let a = [1,2,3,4,5]
let iter = filter(a, x => x>3) // Call the function
// Lets check the returned object of iter.next() method
iter.next() // {value: 4, done: false}
iter.next() // {value: 5, done: false}
iter.next() // {value: undefined, done: true}
I am completely confused about the next() method here. Please help me in understanding it.
Also, I am not able to understand that... the next() method contains an infinite for loop. But what it makes it break that loop. There is no condition like that here.
Thanks in Advance