Chunk generic batching for fixed-size batches

Go
package chunks

// Chunk splits items into consecutive slices of at most size elements.
// It returns nil for a non-positive size and copies each batch, so callers can
// mutate a batch without touching the source slice.
func Chunk[T any](items []T, size int) [][]T {
    if size <= 0 {
        return nil
    }
    out := make([][]T, 0, (len(items)+size-1)/size)
    for start := 0; start < len(items); start += size {
        end := start + size
        if end > len(items) {
            end = len(items)
        }
        batch := make([]T, end-start)
        copy(batch, items[start:end])
        out = append(out, batch)
    }
    return out
}