iterator
is used quite often, e.g. in spread
operator, for/of
-loop, in deconstructing, etc. But they are hidden. I wonder whether there are use cases where you would actively use the knowledge of how to implement an iterator?
For example, iterating over an array using an iterator is over complicated, as you can see below, and I wouldn't know why someone would implement an iterator by himself:
function arrayIterable(arr = []) {
let index = 0;
const len = arr.length;
const arrayIterator = {
next: () => {
let result;
if (index === len) {
return { value: arr[index], done: true };
}
result = { value: arr[index], done: false }
index++;
return result;
}
};
return arrayIterator;
}
const myArr = ['a','b','c','d'];
let iter = arrayIterator(myArr);
let result = iter.next();
while (!result.done) {
console.log(result.value);
result = iter.next();
}