Created
November 20, 2023 17:03
-
-
Save rvflash/ce9d0ea2c87402fabaa38d0a7d5941a3 to your computer and use it in GitHub Desktop.
Generic slices chunk in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package slices defines various functions useful with slices of any type. | |
package slices | |
import "math" | |
// Chunk splits a slice into uniform chunks of the requested size. | |
func Chunk[V any](x []V, size int) [][]V { | |
n := len(x) | |
if n == 0 || size <= 0 { | |
return nil | |
} | |
if n <= size { | |
return [][]V{x} | |
} | |
var ( | |
res = make([][]V, 0, int(math.Ceil(float64(n)/float64(size)))) | |
end int | |
) | |
for i := 0; i < n; i += size { | |
end = i + size | |
if end > n { | |
end = n | |
} | |
res = append(res, x[i:end]) | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment