-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add `utils.ChunkSlice` * ensure test hits edge case
- Loading branch information
1 parent
ea92ea3
commit 0207d48
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
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
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 | ||
} |
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
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) | ||
} | ||
} | ||
} |