Skip to content

Commit

Permalink
Address PR comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Zijun Wang committed Nov 2, 2023
1 parent a2d8ade commit 33cb4f4
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 24 deletions.
3 changes: 3 additions & 0 deletions pkg/utils/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ func min[T constraints.Ordered](a, b T) T {

func Chunks[T any](in []T, size int) [][]T {
out := [][]T{}
if size <= 0 {
return out
}
for low := 0; low < len(in); low += size {
high := min(low+size, len(in))
out = append(out, in[low:high])
Expand Down
90 changes: 66 additions & 24 deletions pkg/utils/common_test.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,78 @@
package utils

import (
"reflect"
"testing"

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

func TestChunks(t *testing.T) {
size := 2
obj1 := &struct{}{}
obj2 := &struct{}{}
obj3 := &struct{}{}
obj4 := &struct{}{}
obj5 := &struct{}{}

t.Run("[obj1] -> [[obj1]]", func(t *testing.T) {

in := []*struct{}{obj1}
out := Chunks(in, size)
assert.Equal(t, [][]*struct{}{{obj1}}, out)

})

t.Run("[obj1,obj2] -> [[obj1,obj2]]", func(t *testing.T) {

in := []*struct{}{obj1, obj2}
got := Chunks(in, size)
assert.Equal(t, [][]*struct{}{{obj1, obj2}}, got)

})

t.Run("[obj1, obj2, obj3] -> [[obj1,obj2],[obj3]]", func(t *testing.T) {
in := []*struct{}{obj1, obj2, obj3}
got := Chunks(in, size)
assert.Equal(t, [][]*struct{}{{obj1, obj2}, {obj3}}, got)
})
type testCase struct {
name string
in []*struct{}
size int
want [][]*struct{}
}
tests := []testCase{
{
name: "[] -> []",
in: []*struct{}{},
size: 2,
want: [][]*struct{}{},
},
{
name: "[obj1] -> [[obj1]]",
in: []*struct{}{obj1},
size: 2,
want: [][]*struct{}{{obj1}},
},
{
name: "[obj1, obj2] -> [[obj1,obj2]]",
in: []*struct{}{obj1},
size: 2,
want: [][]*struct{}{{obj1}},
},
{
name: "[obj1, obj2, obj3] -> [[obj1,obj2],[obj3]]",
in: []*struct{}{obj1, obj2, obj3},
size: 2,
want: [][]*struct{}{{obj1, obj2}, {obj3}},
},
{
name: "[obj1, obj2, obj3, obj4] -> [[obj1,obj2],[obj3,obj4]]",
in: []*struct{}{obj1, obj2, obj3, obj4},
size: 2,
want: [][]*struct{}{{obj1, obj2}, {obj3, obj4}},
},
{
name: "[obj1, obj2, obj3, obj4, obj5] -> [[obj1,obj2],[obj3,obj4],[obj5]]",
in: []*struct{}{obj1, obj2, obj3, obj4, obj5},
size: 2,
want: [][]*struct{}{{obj1, obj2}, {obj3, obj4}, {obj5}},
},
{
name: "size 0",
in: []*struct{}{obj1, obj2, obj3, obj4, obj5},
size: 0,
want: [][]*struct{}{},
},
{
name: "negative size",
in: []*struct{}{obj1, obj2, obj3, obj4, obj5},
size: -1,
want: [][]*struct{}{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Chunks(tt.in, tt.size); !reflect.DeepEqual(got, tt.want) {
t.Errorf("Chunks() got %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 33cb4f4

Please sign in to comment.