-
Notifications
You must be signed in to change notification settings - Fork 102
/
Iterator.js
40 lines (34 loc) · 1.02 KB
/
Iterator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
It is a behavioural design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Iterators have a special kind of behavior where we step through an ordered set of values one at a time by calling next() until we reach the end. The introduction of Generators and Iterators in ES6 made the implementation of iterator pattern extremely straightforward.
*/
// using Iterator
class IteratorClass {
constructor(data) {
this.index = 0;
this.data = data;
}
[Symbol.iterator]() {
return {
next: () => {
if (this.index < this.data.length) {
return { value: this.data[this.index++], done: false };
} else {
this.index = 0; // to reset iteration status
return { done: true };
}
},
};
}
}
// using Generator
function* iteratorUsingGenerator(collection) {
var nextIndex = 0;
while (nextIndex < collection.length) {
yield collection[nextIndex++];
}
}
module.exports = {
IteratorClass,
iteratorUsingGenerator,
};