Created
July 3, 2023 11:30
-
-
Save Tylerian/c5e6a10eb9887dfadae3b562a45f121a to your computer and use it in GitHub Desktop.
slice Chunk functions for Golang
This file contains hidden or 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
func Chunk[T any](collection []T, chunkSize int) []T { | |
length := len(collection) | |
remainder := 0 | |
if length%chunkSize > 0 { | |
remainder = 1 | |
} | |
numOfChunks := length/chunkSize + remainder | |
chunks := make([]T, 0, numOfChunks) | |
start, end := 0, 0 | |
for start < length { | |
end = start + chunkSize | |
if end > length { | |
end = length | |
} | |
chunks = append(collection[start:end]) | |
} | |
return chunks | |
} | |
func Test_Chunk(t *testing.T) { | |
t.Run("it chunks slices correctly", func(t *testing.T) { | |
input := []string{"a", "b", "c", "d", "e"} | |
output := Chunk(input, 2) | |
require.Len(t, output, 3) | |
require.EqualValues(t, output[0], []string{"a", "b"}) | |
require.EqualValues(t, output[1], []string{"c", "d"}) | |
require.EqualValues(t, output[2], []string{"e"}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment