forked from ramana4029/es6-features
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerators.js
More file actions
51 lines (40 loc) · 1.02 KB
/
generators.js
File metadata and controls
51 lines (40 loc) · 1.02 KB
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
function* makeSimpleGenerator(array) {
var nextIndex = 0;
while (nextIndex < array.length) {
yield array[nextIndex++];
}
}
var gen = makeSimpleGenerator(['yo', 'ya']);
console.log(gen.next().value); // 'yo'
console.log(gen.next().value); // 'ya'
console.log(gen.next().done); // true
//With a class
class SimpleClass {
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; //If we would like to iterate over this again without forcing manual update of the index
return {done: true};
}
}
}
};
}
const simple = new SimpleClass([1,2,3,4,5]);
for (const val of simple) {
console.log(val); //'0' '1' '2' '3' '4' '5'
}
//Using yield
var aGeneratorObject = function* () {
yield 1;
yield 2;
yield 3;
}();
console.log(aGeneratorObject.next().value);