-
Notifications
You must be signed in to change notification settings - Fork 5
/
rangeIterator.js
107 lines (83 loc) · 1.98 KB
/
rangeIterator.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
function RangeInterator(start = 1, end = Infinity, steps = 1) {
let latest = 0;
this.next = function() {
if(latest <= end) {
if(latest = 0) {
latest = start;
return latest;
}
latest+=steps;
return latest;
}
return { done: true };
}
}
// let it = new RangeInterator(1, 20, 2);
// while(!it.next().done) {
// console.log(it.next());
// }
/*
Generators -> it is used to create iterators
*/
function* rangeIterator(start=1, end=Infinity, steps=1) {
for(let i=start;i<=end;i+=steps) {
yield i;
}
}
// whenever yield keyword gets encountered the execution
// of next function would be returned.
// let it = rangeIterator(1, 20, 4);
// let nextVal = it.next();
// while(!nextVal.done) {
// console.log(nextVal.value);
// nextVal = it.next();
// }
function* generator() {
yield 1;
yield 2;
yield 3;
}
// let it = generator();
// for(let item of it) {
// console.log(item);
// }
// for(let item of it) {
// console.log(item);
// }
//let it = generator();
// console.log(it.next().value);
// console.log(it.next().value);
// console.log(it.next().value);
// console.log(it.next().done);
// when we'll trigger next function it'll
// execute the generator till next yield.
// when there is no yield left then done value would be true.
function* fibonacci() {
let first = 0;
let second = 1;
yield first;
yield second;
while(true) {
let temp = second;
second = first + second;
first = temp;
let reset = yield second;
if(reset) {
first = 0;
second = 1;
}
}
}
// let it = fibonacci();
// let i=0;
// while(i<=5) {
// console.log(it.next().value);
// i++;
// }
// it.next(true);
// console.log(it.next(true).value);
// function* toIterator() {
// yield* ['a', 'b', 'c'];
// }
// let arrIt = toIterator();
// console.log(arrIt.next().value);