Chunk an array in Go

Chunk an array in Go

Hello everyone, I decided to use this blog as a personal book for reminders and discovers. Recently while I was helping a friend with a university exercise, and he had to basically chunk an array. The exercise was asking to reflow a text file; basically given a certain text, and a row length, cut every row in the text at the specified length.

Translated to simple words, he had to literally chunk the text. Below the core function of the exercise solution.

Talk is cheap. Show me the code

func ChunkArray(arr []string, size int) [][]string {
    var chunk [][]string

    for i:=0; i<len(arr); i+=size {
        // We use `Min` to prevent `index out of range`
        chunk = append(chunk, arr[i:Min(i+size, len(arr))])
    }

    return chunk
 }

// no Math.min because it accepts only floats
func Min(a int, b int) int {
    if a < b {
        return a
    }

    return b
}