-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_test.go
108 lines (95 loc) · 1.92 KB
/
example_test.go
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
package kway_test
import (
"fmt"
"iter"
"testing"
"github.com/achille-roussel/kway-go"
)
func ExampleMerge() {
sequence := func(min, max, step int) iter.Seq2[int, error] {
return func(yield func(int, error) bool) {
for i := min; i < max; i += step {
if !yield(i, nil) {
return
}
}
}
}
for value, err := range kway.Merge(
sequence(0, 5, 1), // 0,1,2,3,4
sequence(1, 5, 2), // 1,3
sequence(2, 5, 3), // 2
) {
if err != nil {
panic(err)
}
fmt.Printf("%v,", value)
}
// Output:
// 0,1,1,2,2,3,3,4,
}
func ExampleMergeSlice() {
sequence := func(min, max, step, size int) iter.Seq2[[]int, error] {
return func(yield func([]int, error) bool) {
values := make([]int, size)
for i := min; i < max; i += step {
for j := range values {
values[j] = i + j
}
if !yield(values, nil) {
return
}
}
}
}
for values, err := range kway.MergeSlice(
sequence(0, 5, 1, 2), // [0,1],[1,2],[2,3],[3,4],[4,5]
sequence(1, 5, 2, 2), // [1,2],[3,4]
sequence(2, 5, 3, 2), // [2,3]
) {
if err != nil {
panic(err)
}
for _, value := range values {
fmt.Printf("%v,", value)
}
}
// Output:
// 0,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,
}
func ExampleMerge_Channels(t *testing.T) {
sequence := func(min, max, step int) iter.Seq2[int, error] {
values, done := make(chan int), make(chan struct{})
go func() {
defer close(values)
for i := min; i < max; i += step {
select {
case values <- i:
case <-done:
}
}
}()
return func(yield func(int, error) bool) {
for value := range values {
if !yield(value, nil) {
close(done)
for range values {
} // wait for the goroutine to finish
break
}
}
}
}
for value, err := range kway.Merge(
sequence(0, 5, 1), // 0,1,2,3,4
sequence(1, 5, 2), // 1,3
sequence(2, 5, 3), // 2
) {
if err != nil {
panic(err)
}
fmt.Printf("%v,", value)
}
// Output:
// 0,1,1,2,2,3,3,4,
}