-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.js
77 lines (63 loc) · 1.39 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Javascript Iterator
*/
// for loop issue
let ranks = ['A', 'B', 'C'];
for (let i = 0; i < ranks.length; i++) {
console.log(ranks[i]);
}
// alternative way of for loop
for (let rank of ranks) {
console.log(rank);
}
/**
* Iterators
*/
class Sequence {
constructor(start = 0, end = Infinity, interval = 1) {
this.start = start;
this.end = end;
this.interval = interval;
}
[Symbol.iterator]() {
let counter = 0;
let nextIndex = this.start;
return {
next: () => {
if (nextIndex <= this.end) {
let result = { value: nextIndex, done: false };
nextIndex = nextIndex + this.interval;
counter = counter + 1;
return result;
}
return {
value: counter,
done: true
};
},
return: () => {
console.log('cleaning up......');
return {
value: undefined,
done: true
};
}
};
}
}
let evenNumbers = new Sequence(2, 10, 2);
for (const num of evenNumbers) {
console.log(num); // 2 4 6 8 10
if (num == 2) break;
}
let iterator = evenNumbers[Symbol.iterator]();
let result = iterator.next();
while (!result.done) {
console.log(result.value); // 2, 4, 6, 8, 10
result = iterator.next();
}
let oddNumbers = new Sequence(1, 10, 2);
for (const num of oddNumbers) {
if (num > 7) break;
console.log(num); // 1 3 5 7
}