diff --git a/utils/chunk_slice.go b/utils/chunk_slice.go new file mode 100644 index 0000000..7725a58 --- /dev/null +++ b/utils/chunk_slice.go @@ -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 +} diff --git a/utils/chunk_slice_test.go b/utils/chunk_slice_test.go new file mode 100644 index 0000000..ff93c6a --- /dev/null +++ b/utils/chunk_slice_test.go @@ -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) + } + } +}