8000 Add yield to generators · HowProgrammingWorks/Generator@cd9ff24 · GitHub
[go: up one dir, main page]

Skip to content

Commit cd9ff24

Browse files
committed
Add yield to generators
1 parent a0c9cc4 commit cd9ff24

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

JavaScript/a-generator.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,17 @@
33
// Generator function
44

55
function* genFn(x) {
6-
return x * 2;
6+
yield x * 2;
7+
return x * 3;
78
}
89

910
console.log('genFn =', [genFn]);
1011
console.log('genFn.toString() =', [genFn.toString()]);
11-
console.log('typeof(genFn) =', typeof(genFn));
12+
console.log('typeof genFn =', typeof genFn);
1213
const fnProto = Object.getPrototypeOf(genFn);
1314
console.log('fnProto.constructor.name =', fnProto.constructor.name);
1415

15-
console.log('typeof(genFn(5)) =', typeof(genFn(5)));
16+
console.log('typeof genFn(5) =', typeof genFn(5));
1617
console.log('genFn(5).toString() =', genFn(5).toString());
1718
const genProto = Object.getPrototypeOf(genFn(5));
1819
console.log('genProto =', genProto);
@@ -28,9 +29,11 @@ class Multiplier {
2829
constructor(k) {
2930
this.value = k;
3031
}
32+
3133
* genMethod(a) {
32-
this.value = a * this.value;
33-
return a * this.value;
34+
yield this.value;
35+
this.value = this.value * a;
36+
return this.value;
3437
}
3538
}
3639

@@ -41,8 +44,10 @@ console.log('m1.genMethod(5).next() =', m1.genMethod(5).next());
4144

4245
const m2 = {
4346
value: 2,
47+
4448
* genMethod(a) {
45-
this.value = a * this.value;
49+
yield this.value;
50+
this.value = this.value * a;
4651
return this.value;
4752
}
4853
};

0 commit comments

Comments
 (0)
0