generators
# Node.js
function* generator() {
yield "hello";
yield "world";
}
let gen = generator();
while (true) {
let { value, done } = gen.next();
console.log(value, done);
if (done) {
break;
}
}
// alternatively
for (let value of generator()) {
console.log(value);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Output
hello false
world false
undefined true
hello
world
1
2
3
4
5
2
3
4
5
# Go
package main
import "fmt"
func Generator() chan string {
c := make(chan string)
go func() {
c <- "hello"
c <- "world"
close(c)
}()
return c
}
func GeneratorFunc() func() (string, bool) {
s := []string{"hello", "world"}
i := -1
return func() (string, bool) {
i++
if i >= len(s) {
return "", false
}
return s[i], true
}
}
func main() {
gen := Generator()
for {
value, more := <-gen
fmt.Println(value, more)
if !more {
break
}
}
// alternatively
for value := range Generator() {
fmt.Println(value)
}
// alternatively
genfn := GeneratorFunc()
for {
value, more := genfn()
fmt.Println(value, more)
if !more {
break
}
}
}
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
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
Output
hello true
world true
false
hello
world
hello true
world true
false
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22