Skip to content

Commit

Permalink
Revert "Remove 'tfslices.Chunks'."
Browse files Browse the repository at this point in the history
This reverts commit e5c24d5.
  • Loading branch information
jar-b committed Sep 10, 2024
1 parent 8ef5573 commit 9be946f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
17 changes: 17 additions & 0 deletions internal/slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
39 changes: 39 additions & 0 deletions internal/slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit 9be946f

Please sign in to comment.