Skip to content

Commit

Permalink
feat(exp): add sliceutil package (#489)
Browse files Browse the repository at this point in the history
- Add a Batches utility to split slices into batches.
  • Loading branch information
jooola authored Jul 22, 2024
1 parent 8313c91 commit f4ad6bc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
9 changes: 9 additions & 0 deletions hcloud/exp/kit/sliceutil/slice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package sliceutil

// Batches splits a slice into multiple batches of a desired size.
func Batches[T any](all []T, size int) (batches [][]T) {
for size < len(all) {
all, batches = all[size:], append(batches, all[:size])
}
return append(batches, all)
}
17 changes: 17 additions & 0 deletions hcloud/exp/kit/sliceutil/slice_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package sliceutil

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestBatches(t *testing.T) {
all := []int{1, 2, 3, 4, 5}
batches := Batches(all, 2)

assert.Len(t, batches, 3)
assert.Equal(t, []int{1, 2}, batches[0])
assert.Equal(t, []int{3, 4}, batches[1])
assert.Equal(t, []int{5}, batches[2])
}

0 comments on commit f4ad6bc

Please sign in to comment.