-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatch.go
34 lines (30 loc) · 823 Bytes
/
batch.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
package batchutil
import (
"errors"
)
// BatchFunc is called for each batch.
// Any error will cancel the batching operation but returning ErrAbort
// indicates it was deliberate, and not an error case.
type BatchFunc[T any] func([]T) error
// ErrAbort indicates that the operation was aborted deliberately.
var ErrAbort = errors.New("done")
// All calls eachFn for all items
// Returns any error from eachFn except for Abort it returns nil.
func All[T any](data []T, batchSize int, eachFn BatchFunc[T]) error {
count := len(data)
for i := 0; i < count; i += batchSize {
end := i + batchSize
if end > count {
end = count
}
batch := make([]T, end-i)
copy(batch, data[i:end])
err := eachFn(batch)
if errors.Is(err, ErrAbort) {
return nil
} else if err != nil {
return err
}
}
return nil
}