Skip to content

Batch a slice for bulk writes

easy

You are writing rows to an API that accepts at most N per request. Split the slice into consecutive batches of size n, where the last batch may be shorter. Getting the final short batch right is the whole exercise.

Signature

func Chunk(items []int, n int) [][]int

Examples

  • Chunk([]int{1,2,3,4,5}, 2) → [[1 2] [3 4] [5]]
  • Chunk([]int{1,2}, 5) → [[1 2]]
  • Chunk([]int{}, 3) → [] (no batches)
  • Chunk([]int{1,2,3}, 0) → [] (a batch size of 0 has no meaning)

Constraints

  • The last batch may be shorter than n
  • Return an empty, non-nil result for empty input or n < 1
  • Batches must be in order and cover every element exactly once