ChunkStrings cuts a slice into consecutive pieces of at most the requested size, with the leftovers in the last piece, and returns copies so the pieces cannot disturb each other. Comes with a doc comment and table-driven tests. (closes #3) Model: opus-5
27 lines
715 B
Go
27 lines
715 B
Go
package util
|
|
|
|
// ChunkStrings splits input into consecutive slices of at most size elements.
|
|
// The last slice holds whatever is left over and may be shorter than the
|
|
// others. Each returned slice is a copy, so appending to one of them cannot
|
|
// disturb another. A size below one, or an empty input, returns nil.
|
|
func ChunkStrings(input []string, size int) [][]string {
|
|
if size < 1 || len(input) == 0 {
|
|
return nil
|
|
}
|
|
|
|
out := make([][]string, 0, (len(input)+size-1)/size)
|
|
|
|
for start := 0; start < len(input); start += size {
|
|
end := start + size
|
|
if end > len(input) {
|
|
end = len(input)
|
|
}
|
|
|
|
chunk := make([]string, end-start)
|
|
copy(chunk, input[start:end])
|
|
out = append(out, chunk)
|
|
}
|
|
|
|
return out
|
|
}
|