Skip to content

Commit

Permalink
Chunk (#184)
Browse files Browse the repository at this point in the history
Chunk splits the input and returns multi slices whose length equals
chunkLength, except for the last slice which may contain fewer elements.

Co-authored-by: morrisyang <[email protected]>
  • Loading branch information
morrisxyang and morrisyang authored Jan 9, 2023
1 parent ab43b76 commit 9f03773
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
39 changes: 39 additions & 0 deletions v2/chunk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package pie

// Chunk splits the input and returns multi slices whose length equals chunkLength,
// except for the last slice which may contain fewer elements.
//
// Examples:
//
// Chunk([1, 2, 3], 4) => [ [1, 2, 3] ]
// Chunk([1, 2, 3], 3) => [ [1, 2, 3] ]
// Chunk([1, 2, 3], 2) => [ [1, 2], [3] ]
// Chunk([1, 2, 3], 1) => [ [1], [2], [3] ]
// Chunk([], 1) => [ [] ]
// Chunk([1, 2, 3], 0) => panic: chunkLength should be greater than 0
func Chunk[T any](ss []T, chunkLength int) [][]T {
if chunkLength <= 0 {
panic("chunkLength should be greater than 0")
}

result := make([][]T, 0)
l := len(ss)
if l == 0 {
return result
}

var step = l / chunkLength
if step == 0 {
result = append(result, ss)
return result
}
var remain = l % chunkLength
for i := 0; i < step; i++ {
result = append(result, ss[i*chunkLength:(i+1)*chunkLength])
}
if remain != 0 {
result = append(result, ss[step*chunkLength:l])
}

return result
}
28 changes: 28 additions & 0 deletions v2/chunk_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package pie

import (
"testing"

"github.com/stretchr/testify/assert"
)

var chunkTests = []struct {
ss []int
chunkLength int
expected [][]int
}{
{nil, 1, [][]int{}},
{[]int{}, 1, [][]int{}},
{[]int{1, 2, 3}, 4, [][]int{{1, 2, 3}}},
{[]int{1, 2, 3}, 3, [][]int{{1, 2, 3}}},
{[]int{1, 2, 3}, 2, [][]int{{1, 2}, {3}}},
{[]int{1, 2, 3}, 1, [][]int{{1}, {2}, {3}}},
}

func TestChunk(t *testing.T) {
for _, test := range chunkTests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.expected, Chunk(test.ss, test.chunkLength))
})
}
}

0 comments on commit 9f03773

Please sign in to comment.