Debian Codegraph @

exslices/chunk.go

raw
1 // Copyright (c) 2024 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package exslices
8
9 // Chunk splits a slice into chunks of the given size.
10 //
11 // From https://github.com/golang/go/issues/53987#issuecomment-1224367139
12 //
13 // TODO remove this after slices.Chunk can be used (it'll probably be added in Go 1.23, so it can be used after 1.22 is EOL)
14 func Chunk[T any](slice []T, size int) (chunks [][]T) {
15 if size < 1 {
16 panic("chunk size cannot be less than 1")
17 }
18 for i := 0; ; i++ {
19 next := i * size
20 if len(slice[next:]) > size {
21 end := next + size
22 chunks = append(chunks, slice[next:end:end])
23 } else {
24 chunks = append(chunks, slice[i*size:])
25 return
26 }
27 }
28 }