Skip to content

Commit

Permalink
slice: make Chunks return its input on n == 0
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Feb 22, 2024
1 parent 2b19650 commit 62448a5
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
7 changes: 4 additions & 3 deletions slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,11 +255,12 @@ func Coalesce[T comparable](vs ...T) T {
// have length exactly n; the last may have fewer. The slices returned share
// storage with the input.
//
// Chunks will panic if n ≤ 0.
// Chunks will panic if n < 0. If n == 0, Batches returns a single chunk
// containing the entire input.
func Chunks[T any, Slice ~[]T](vs Slice, n int) []Slice {
if n <= 0 {
if n < 0 {
panic("max must be positive")
} else if n >= len(vs) {
} else if n == 0 || n >= len(vs) {
return []Slice{vs}
}
out := make([]Slice, 0, (len(vs)+n-1)/n)
Expand Down
4 changes: 3 additions & 1 deletion slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,12 +334,15 @@ func TestChunks(t *testing.T) {
want [][]string
}{
// An empty slice has only one covering.
{"", 0, [][]string{{}}},
{"", 1, [][]string{{}}},
{"", 5, [][]string{{}}},

{"x", 0, [][]string{{"x"}}},
{"x", 1, [][]string{{"x"}}},
{"x", 2, [][]string{{"x"}}},

{"a b c d e", 0, [][]string{{"a", "b", "c", "d", "e"}}},
{"a b c d e", 1, [][]string{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}},
{"a b c d e", 2, [][]string{{"a", "b"}, {"c", "d"}, {"e"}}},
{"a b c d e", 3, [][]string{{"a", "b", "c"}, {"d", "e"}}},
Expand All @@ -359,7 +362,6 @@ func TestChunks(t *testing.T) {
}
}

t.Logf("OK n=0: %v", mtest.MustPanic(t, func() { slice.Chunks([]string{"a"}, 0) }))
t.Logf("OK n<0: %v", mtest.MustPanic(t, func() { slice.Chunks([]string{"a"}, -1) }))
}

Expand Down

0 comments on commit 62448a5

Please sign in to comment.