-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerators.js
125 lines (95 loc) · 2.29 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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*jshint esversion: 6 */
// Generators
// Usually used to iterate through complex data structures
function* shopping() {
const stuffFromStore = yield 'cash';
const cleanClothes = yield 'laundry';
return [stuffFromStore, cleanClothes];
}
const gen = shopping();
gen.next();
gen.next('groceries');
gen.next('clean clothes');
console.log(gen);
function* colors() {
yield 'red';
yield 'blue';
yield 'green';
}
const colorGen = colors();
colorGen.next(); // { value: red, done: false }
colorGen.next(); // { value: blue, done: false }
colorGen.next(); // { value: green, done: false }
console.log(colorGen.next()); // { value: undefined, done: true }
const myColors = [];
for (let color of colors()) {
myColors.push(color);
}
console.log(myColors); // [ 'red', 'blue', 'green' ]
const testingTeam = {
lead: 'Amanda',
tester: 'Bill',
// Symbol.iterator tells a for of loop how
// it should iterate through an object
[Symbol.iterator]: function* () {
yield this.lead;
yield this.tester;
}
};
const engineeringTeam = {
testingTeam,
size: 3,
department: 'Engineering',
lead: 'Jill',
manager: 'Alex',
engineer: 'Dave',
// Move our teamIterator generator here
[Symbol.iterator]: function* () {
yield this.lead;
yield this.manager;
yield this.engineer;
yield* this.testingTeam;
}
};
// function* teamIterator(team) {
// yield team.lead;
// yield team.manager;
// yield team.engineer;
//
// // Loop over the testingTeams Symbol.iterator
// yield* team.testingTeam;
// }
const names = [];
for(let name of engineeringTeam) {
names.push(name);
}
console.log(names);
// Use case
class Comment {
constructor(content, children) {
this.content = content;
this.children = children;
}
// A generator inside a class
*[Symbol.iterator]() {
yield this.content;
for(let child of this.children) {
yield* child;
}
}
}
const grandChildren = [
new Comment('GrandChild comment1!', []),
new Comment('GrandChild comment2!', []),
];
const children = [
new Comment('good comment', grandChildren),
new Comment('bad comment', []),
new Comment('meh comment', []),
];
const root = new Comment('Great Post!', children);
const values = [];
for (let value of root) {
values.push(value);
}
console.log(values);