add ChunkStrings for splitting a string slice into fixed-size batches
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
This commit is contained in:
26
chunk.go
Normal file
26
chunk.go
Normal file
@@ -0,0 +1,26 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user