-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17-generators.js
More file actions
95 lines (82 loc) · 2.15 KB
/
17-generators.js
File metadata and controls
95 lines (82 loc) · 2.15 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
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
// a generator is a function that can pause execution
// and return a different value on successive calls
// a generator returns an object which consists of a value
// and a flag to indicate if the function has finished
function * genfunction() {
// things to do before yielding a value
const upstreamValue = yield 'someValue';
// things to do before being finished
return upstreamValue;
}
const gen = genfunction();
console.log(gen); // {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: undefined}
gen.next(); // {"value":"someValue","done":false}
gen.next('otherValue'); // {"value":"otherValue","done":false}
//------------------
// a generator with multiple yields
function * colors() {
yield 'red';
yield 'blue';
yield 'green';
}
// one way to access all the yields
const gen = colors();
gen.next(); // {"value":"red","done":false}
gen.next(); // {"value":"blue","done":false}
gen.next(); // {"value":"green","done":false}
gen.next(); // {"done":true}
// another
const myColors = [];
for( let color of colors()) {
myColors.push(color);
}
myColors; // ["red","blue","green"]
//------------------
// using a generator to iterate specific fields of an object
const engineeringTeam = {
size: 3,
department: 'Engineering',
lead: 'Jill',
manager: ' Alex',
engineer: 'Dave',
}
function * TeamIterator(team) {
yield team.lead;
yield team.manager;
yield team.engineer
}
const names = [];
for( let name of TeamIterator(engineeringTeam)) {
names.push(name);
}
names; // ['Jill','Alex','Dave']
//------------------
// delegating generators
const testingTeam = {
lead: 'Amanda',
tester: 'Bill'
}
const engineeringTeam = {
testingTeam,
size: 3,
department: 'Engineering',
lead: 'Jill',
manager: ' Alex',
engineer: 'Dave',
}
function * TestTeamIterator(team) {
yield team.lead;
yield team.tester
}
function * TeamIterator(team) {
yield team.lead;
yield team.manager;
yield team.engineer
const testingTeamGenerator = TestTeamIterator(team.testingTeam);
yield* testingTeamGenerator;
}
const names = [];
for( let name of TeamIterator(engineeringTeam)) {
names.push(name);
}
names; // ["Jill"," Alex","Dave","Amanda","Bill"]