-
Notifications
You must be signed in to change notification settings - Fork 725
/
utils.go
51 lines (44 loc) · 974 Bytes
/
utils.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
package base
import (
"fmt"
"time"
)
func EventKey(source string, subject string) string {
return fmt.Sprintf("%s.%s", source, subject)
}
// Batch returns a read only channel that receives values from the
// input channel batched together into a slice. A value is sent to
// the output channel when the slice reaches n elements, or d time
// has elapsed, whichever happens first. Ordering is maintained.
func Batch[T any](n int, d time.Duration, in <-chan T) <-chan []T {
out := make(chan []T, 1)
go func() {
batch := []T{}
timer := time.NewTimer(d)
timer.Stop()
defer close(out)
defer timer.Stop()
for {
select {
case item, ok := <-in:
if !ok {
return
}
if len(batch) == 0 {
timer.Reset(d)
}
if batch = append(batch, item); len(batch) == n {
timer.Stop()
out <- batch
batch = nil
}
case <-timer.C:
if len(batch) > 0 {
out <- batch
batch = nil
}
}
}
}()
return out
}