Skip to content

Commit b90cb8a

Browse files
committed
Add Get Chunks for an array of interfaces
1 parent c5d526f commit b90cb8a

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

slice/batch.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package slice
2+
3+
import (
4+
"errors"
5+
"reflect"
6+
)
7+
8+
func GetChunks(slice interface{}, size uint) ([][]interface{}, error) {
9+
interfaceSlice, err := GetInterfaceSlice(slice)
10+
if err != nil {
11+
return nil, err
12+
}
13+
14+
return GetInterfaceSliceBatch(interfaceSlice, size), nil
15+
}
16+
17+
func GetInterfaceSlice(slice interface{}) ([]interface{}, error) {
18+
s := reflect.ValueOf(slice)
19+
if s.Kind() != reflect.Slice {
20+
return nil, errors.New("InterfaceSlice() given a non-slice type")
21+
}
22+
23+
ret := make([]interface{}, s.Len())
24+
25+
for i := 0; i < s.Len(); i++ {
26+
ret[i] = s.Index(i).Interface()
27+
}
28+
29+
return ret, nil
30+
}
31+
32+
func GetInterfaceSliceBatch(values []interface{}, sizeUint uint) (chunks [][]interface{}) {
33+
size := int(sizeUint)
34+
resultLength := (len(values) + size - 1) / size
35+
result := make([][]interface{}, resultLength)
36+
lo, hi := 0, size
37+
for i := range result {
38+
if hi > len(values) {
39+
hi = len(values)
40+
}
41+
result[i] = values[lo:hi:hi]
42+
lo, hi = hi, hi+size
43+
}
44+
return result
45+
//shorter version (https://gist.github.com/mustafaturan/7a29e8251a7369645fb6c2965f8c2daf)
46+
//for int(sizeUint) < len(values) {
47+
// values, chunks = values[sizeUint:], append(chunks, values[0:sizeUint:sizeUint])
48+
//}
49+
//return append(chunks, values)
50+
}

slice/batch_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package slice
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestGetSlice(t *testing.T) {
10+
type args struct {
11+
slice []uint
12+
size uint
13+
}
14+
15+
tests := []struct {
16+
name string
17+
args args
18+
want [][]uint
19+
wantErr bool
20+
}{
21+
{
22+
"Test uint batch size of 2",
23+
args{
24+
[]uint{1, 2, 3, 4}, 2,
25+
},
26+
[][]uint{{1, 2}, {3, 4}},
27+
false,
28+
},
29+
}
30+
for _, tt := range tests {
31+
t.Run(tt.name, func(t *testing.T) {
32+
got, err := GetSlice(tt.args.slice, tt.args.size)
33+
if (err != nil) != tt.wantErr {
34+
t.Errorf("GetSlice() error = %v, wantErr %v", err, tt.wantErr)
35+
return
36+
}
37+
assert.Equal(t, tt.want, got)
38+
})
39+
}
40+
}

0 commit comments

Comments
 (0)