Skip to content

Commit f4ad6bc

Browse files
authored
feat(exp): add sliceutil package (#489)
- Add a Batches utility to split slices into batches.
1 parent 8313c91 commit f4ad6bc

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

hcloud/exp/kit/sliceutil/slice.go

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package sliceutil
2+
3+
// Batches splits a slice into multiple batches of a desired size.
4+
func Batches[T any](all []T, size int) (batches [][]T) {
5+
for size < len(all) {
6+
all, batches = all[size:], append(batches, all[:size])
7+
}
8+
return append(batches, all)
9+
}
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package sliceutil
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestBatches(t *testing.T) {
10+
all := []int{1, 2, 3, 4, 5}
11+
batches := Batches(all, 2)
12+
13+
assert.Len(t, batches, 3)
14+
assert.Equal(t, []int{1, 2}, batches[0])
15+
assert.Equal(t, []int{3, 4}, batches[1])
16+
assert.Equal(t, []int{5}, batches[2])
17+
}

0 commit comments

Comments
 (0)