Iterator
Introduction
// 1st Method
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
let nextIndex = start;
let iterationCount = 0;
const rangeIterator = {
next() {
let result;
if (nextIndex < end) {
result = { value: nextIndex, done: false };
nextIndex += step;
iterationCount++;
return result;
}
return { value: iterationCount, done: true };
},
};
return rangeIterator;
}
// 2nd Method (By Generator Function)
function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
let iterationCount = 0;
for (let i = start; i < end; i += step) {
iterationCount++;
yield i;
}
return iterationCount;
}
const iter = makeRangeIterator(1, 10, 2);
// 3rd Method (By declaring symbol iterator)
const iter = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
yield 5;
yield 7;
yield 9;
},
};
console.log(iter[Symbol.iterator]() === iter); // true
// 1st Looping Sequence Method
let result = iter.next();
while (!result.done) {
console.log(result.value); // 1 3 5 7 9
result = iter.next();
}
// 2nd Looping Sequence Method
for (const itItem of iter) {
console.log(itItem); // 1 3 5 7 9
}Inheritance
Built-in Iterable Object
Last updated