From 431c7ce332e6dfec058e56e3e239603a10a6410b Mon Sep 17 00:00:00 2001 From: jo Date: Fri, 19 Jul 2024 11:44:27 +0200 Subject: [PATCH 1/2] feat(exp): add sliceutil package --- hcloud/exp/kit/sliceutil/slice.go | 8 ++++++++ hcloud/exp/kit/sliceutil/slice_test.go | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 hcloud/exp/kit/sliceutil/slice.go create mode 100644 hcloud/exp/kit/sliceutil/slice_test.go diff --git a/hcloud/exp/kit/sliceutil/slice.go b/hcloud/exp/kit/sliceutil/slice.go new file mode 100644 index 00000000..884953c4 --- /dev/null +++ b/hcloud/exp/kit/sliceutil/slice.go @@ -0,0 +1,8 @@ +package sliceutil + +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) +} diff --git a/hcloud/exp/kit/sliceutil/slice_test.go b/hcloud/exp/kit/sliceutil/slice_test.go new file mode 100644 index 00000000..75e94f4a --- /dev/null +++ b/hcloud/exp/kit/sliceutil/slice_test.go @@ -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]) +} From 4e4323510cd2380d1b4d2f95be7345763cc5a562 Mon Sep 17 00:00:00 2001 From: jo Date: Fri, 19 Jul 2024 11:46:00 +0200 Subject: [PATCH 2/2] docs --- hcloud/exp/kit/sliceutil/slice.go | 1 + 1 file changed, 1 insertion(+) diff --git a/hcloud/exp/kit/sliceutil/slice.go b/hcloud/exp/kit/sliceutil/slice.go index 884953c4..3f035f6a 100644 --- a/hcloud/exp/kit/sliceutil/slice.go +++ b/hcloud/exp/kit/sliceutil/slice.go @@ -1,5 +1,6 @@ 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])