Skip to content

Commit

Permalink
add utils.ChunkSlice (#23)
Browse files Browse the repository at this point in the history
* add `utils.ChunkSlice`

* ensure test hits edge case
  • Loading branch information
aidenwallis authored Mar 20, 2023
1 parent ea92ea3 commit 0207d48
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
14 changes: 14 additions & 0 deletions utils/chunk_slice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package utils

// ChunkSlice splits a slice into chunks of a given size.
func ChunkSlice[T any](s []T, chunkSize int) [][]T {
var chunks [][]T
for i := 0; i < len(s); i += chunkSize {
end := i + chunkSize
if end > len(s) {
end = len(s)
}
chunks = append(chunks, s[i:end])
}
return chunks
}
24 changes: 24 additions & 0 deletions utils/chunk_slice_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package utils_test

import (
"testing"

"github.com/aidenwallis/go-utils/internal/assert"
"github.com/aidenwallis/go-utils/utils"
)

func TestChunkSlice(t *testing.T) {
t.Parallel()

in := []int{1, 2, 3, 4, 5, 6, 7, 8}
expected := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8}}

out := utils.ChunkSlice(in, 3)

for i, chunk := range out {
assert.Equal(t, len(expected[i]), len(chunk))
for j, v := range chunk {
assert.Equal(t, expected[i][j], v)
}
}
}

0 comments on commit 0207d48

Please sign in to comment.