Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions chunk.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ package hoff
// Chunk takes an input array of T elements, and "chunks" into groups of chunkSize elements.
// If the input array is empty, or the batchSize is 0, return an empty slice of slices.
// Adapted to generics from https://github.com/golang/go/wiki/SliceTricks#batching-with-minimal-allocation.
// Examples:
// Chunk([]int{1, 2, 3, 4, 5}, 2) = [[1, 2] [3, 4], [5]]
// Chunk([]int{}, 2) = []
// Chunk([]int{1, 2, 3}, 0) = [].
func Chunk[T any](actions []T, batchSize int) [][]T {
// if the input is empty or batch size is 0, return an empty slice of slices
if len(actions) == 0 || batchSize < 1 {
Expand Down
16 changes: 16 additions & 0 deletions chunk_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package hoff

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -114,3 +115,18 @@ func TestChunkStructs(t *testing.T) {
require.Equal(t, testCase.ExpectedOutput, output, testCase.Message)
}
}

func ExampleChunk() {
fmt.Println(Chunk([]int{1, 2, 3, 4, 5}, 2))
// Output: [[1 2] [3 4] [5]]
}

func ExampleChunk_withEmptyArray() {
fmt.Println(Chunk([]int{}, 2))
// Output: []
}

func ExampleChunk_zeroBatchSize() {
fmt.Println(Chunk([]int{1, 2, 3}, 0))
// Output: []
}