-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcombine.go
59 lines (54 loc) · 1.48 KB
/
combine.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
package jpipe
import (
"sync"
)
// Merge merges multiple input channels to a single output channel. Values from input
// channels are sent to the output channel as they arrive, with no specific priority.
//
// Example:
//
// output := Merge(input1, input2)
//
// input1: 0----1----2------3-X
// input2: -----5------6------X
// output: 0----5-1--2-6----3-X
func Merge[T any](inputs ...*Channel[T]) *Channel[T] {
worker := func(node workerNode[T, T]) {
var wg sync.WaitGroup
for i := range inputs {
i := i // avoid goroutine capturing the loop i
wg.Add(1)
go func() {
defer wg.Done()
node.LoopInput(i, func(value T) bool {
return node.Send(value)
})
}()
}
wg.Wait()
}
_, output := newPipelineNode("Merge", inputs[0].getPipeline(), inputs, 1, worker, false)
return output[0]
}
// Concat concatenates multiple input channels to a single output channel.
// Channels are consumed in order, e.g., the second channel won't be consumed
// until the first channel is closed.
//
// Example:
//
// output := Concat(input1, input2)
//
// input 1: 0----1----2------3-X
// input 2: -----5------6--------------7--X
// output : 0----1----2------3-5-6-----7--X
func Concat[T any](inputs ...*Channel[T]) *Channel[T] {
worker := func(node workerNode[T, T]) {
for i := range inputs {
node.LoopInput(i, func(value T) bool {
return node.Send(value)
})
}
}
_, output := newPipelineNode("Concat", inputs[0].getPipeline(), inputs, 1, worker, false)
return output[0]
}