-
Notifications
You must be signed in to change notification settings - Fork 0
/
generators.js
64 lines (53 loc) · 1.15 KB
/
generators.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
//generator func which will alwz return a uniq ID
function* uniqeID() {
while (true) {
yield Math.random();
}
}
console.log(uniqeID().next().value);
console.log(uniqeID().next().value);
console.log(uniqeID().next().value);
function* main() {
for (let i = 0; i < 8; i++) yield i;
}
console.log([...main()]);
for (v of main()) {
console.log(v);
}
//maing an object iterable using generators
const obj = {
*[Symbol.iterator]() {
let index = this.start,
end = this.end;
while (index < end) {
yield this.values[index];
index++;
}
},
values: [1, 22, 33, 55, 44, 12, 43, 56, 99, 12, 34, 34],
start: 2,
end: 8
};
console.log([...obj]);
for (v of obj) {
console.log(v);
}
//numbers object with an iterable method
const numbers = {
*[Symbol.iterator]({ step = 1, start = 0, end = 100 } = {}) {
for (let i = start; i <= end; i += step) yield i;
}
};
//should print from 0 to 100 by 1step
for (let num of numbers) {
console.log(num);
}
console.log("--------------------");
//should print from 6 to 40 by 2steps
for (let num of numbers[Symbol.iterator]({
step: 2,
start: 6,
end: 40
})) {
console.log(num);
}