Iterators
Iterator object is an object that obeys the Iterator Protocol.
Iterator Protocol :
A Standard way of producing a sequence of values.
These values can be finite or infinite.
An iterator object implements the next method with the following rules:
next-method next()
A function that accepts zero or one argument and returns an object with the following interface.
done - optional
It is a boolean value. When there are no more values to iterate or the stop condition has been reached it turns false.
value - optional
The next value during iteration
const fruits = ["apple", "oranges", "grapes", "watermelon", "papaya"];
function fruitsIterator(frValues) {
let nextFruitIndex = 0;
return {
next: function () {
if (nextFruitIndex < frValues.length) {
return {
value: frValues[nextFruitIndex++],
done: false
};
} else {
return {
done: true
};
}
}
};
}
// using an iterator
const fruitsIt = fruitsIterator(fruits);
console.log(fruitsIt.next());
console.log(fruitsIt.next());
console.log(fruitsIt.next());
console.log(fruitsIt.next());
console.log(fruitsIt.next());
console.log(fruitsIt.next());
You can create your iterators and make them iterate as per any business logic.
All iterable items (Arrays, Maps, Sets etc) have [Symbol.iterator] property which can be used to design a custom iterator.
Objects do not have [Symbol.Iterator] property and hence we cannot use for .. of loop to iterate. We can use for .. in . (\for(key in object))*
const fruits = ["apple", "oranges", "grapes", "watermelon", "papaya"];
const evenIdxFruitsIterator = {
[Symbol.iterator]: function () {
let nextFruitIndex = 0;
return {
next: function () {
if (nextFruitIndex < fruits.length) {
let tempIdx = nextFruitIndex;
nextFruitIndex += 2;
return {
value: fruits[tempIdx],
done: false
};
} else {
return {
done: true
};
}
}
};
}
};
const custIte = evenIdxFruitsIterator[Symbol.iterator]();
console.log(custIte.next()); //{value: "apple", done: false}
console.log(custIte.next()); //{value: "grapes", done: false}
console.log(custIte.next()); //{value: "papaya", done: false}
console.log(custIte.next()); //{done: true}
console.log(custIte.next()); //{done: true}