From 9be946fa22ed578bcf3beb25c76b2c9e3ee52e0a Mon Sep 17 00:00:00 2001 From: Jared Baker Date: Tue, 10 Sep 2024 11:24:49 -0400 Subject: [PATCH] Revert "Remove 'tfslices.Chunks'." This reverts commit e5c24d5d41a5d074b679074e6091c9f2583e88e6. --- internal/slices/slices.go | 17 +++++++++++++++ internal/slices/slices_test.go | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/internal/slices/slices.go b/internal/slices/slices.go index f35b30007b3..dccfa9f3814 100644 --- a/internal/slices/slices.go +++ b/internal/slices/slices.go @@ -100,6 +100,23 @@ func Any[S ~[]E, E any](s S, f Predicate[E]) bool { return false } +// Chunks returns a slice of S, each of the specified size (or less). +func Chunks[S ~[]E, E any](s S, size int) []S { + chunks := make([]S, 0) + + for i := 0; i < len(s); i += size { + end := i + size + + if end > len(s) { + end = len(s) + } + + chunks = append(chunks, s[i:end]) + } + + return chunks +} + // AppendUnique appends unique (not already in the slice) values to a slice. func AppendUnique[S ~[]E, E comparable](s S, vs ...E) S { for _, v := range vs { diff --git a/internal/slices/slices_test.go b/internal/slices/slices_test.go index 0537d29f2cf..35ea97b2621 100644 --- a/internal/slices/slices_test.go +++ b/internal/slices/slices_test.go @@ -153,6 +153,45 @@ func TestApplyToAll(t *testing.T) { } } +func TestChunk(t *testing.T) { + t.Parallel() + + type testCase struct { + input []string + expected [][]string + } + tests := map[string]testCase{ + "three elements": { + input: []string{"one", "two", "3"}, + expected: [][]string{{"one", "two"}, {"3"}}, + }, + "two elements": { + input: []string{"aa", "bb"}, + expected: [][]string{{"aa", "bb"}}, + }, + "one element": { + input: []string{"1"}, + expected: [][]string{{"1"}}, + }, + "zero elements": { + input: []string{}, + expected: [][]string{}, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + t.Parallel() + + got := Chunks(test.input, 2) + + if diff := cmp.Diff(got, test.expected); diff != "" { + t.Errorf("unexpected diff (+wanted, -got): %s", diff) + } + }) + } +} + func TestFilter(t *testing.T) { t.Parallel()