Skip to content

Commit

Permalink
Add slicehelpers.Chunks
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Aug 26, 2022
1 parent f365b15 commit 3dbafd8
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
23 changes: 23 additions & 0 deletions slicehelpers/slicehelpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package slicehelpers

// Chunk splits the slice s into n number of chunks.
func Chunk[T any](s []T, n int) [][]T {
if len(s) == 0 {
return nil
}
var partitions [][]T
sizeDefault := len(s) / n
sizeBig := len(s) - sizeDefault*n
size := sizeDefault + 1
for i, idx := 0, 0; i < n; i++ {
if i == sizeBig {
size--
if size == 0 {
break
}
}
partitions = append(partitions, s[idx:idx+size])
idx += size
}
return partitions
}
66 changes: 66 additions & 0 deletions slicehelpers/slicehelpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package slicehelpers

import (
"testing"

qt "github.com/frankban/quicktest"
)

func TestChunk(t *testing.T) {
c := qt.New(t)
c.Assert(Chunk(
[]int{1, 2, 3, 4, 5}, 2),
qt.DeepEquals,
[][]int{
{1, 2, 3},
{4, 5},
},
)

c.Assert(Chunk(
[]int{1, 2}, 3),
qt.DeepEquals,
[][]int{
{1},
{2},
},
)

c.Assert(Chunk(
[]int{1}, 2),
qt.DeepEquals,
[][]int{
{1},
},
)

c.Assert(Chunk(
[]int{}, 2),
qt.IsNil,
)

c.Assert(
Chunk([]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}, 3),
qt.DeepEquals,
[][]string{
{"a", "b", "c", "d", "e", "f", "g", "h", "i"},
{"j", "k", "l", "m", "n", "o", "p", "q", "r"},
{"s", "t", "u", "v", "w", "x", "y", "z"},
},
)

c.Assert(
Chunk([]string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}, 7),
qt.DeepEquals,
[][]string{
{"a", "b", "c", "d"},
{"e", "f", "g", "h"},
{"i", "j", "k", "l"},
{"m", "n", "o", "p"},
{"q", "r", "s", "t"},
{"u", "v", "w"},
{"x", "y", "z"},
},
)

}

0 comments on commit 3dbafd8

Please sign in to comment.