Created
July 16, 2023 17:33
-
-
Save Th3Shadowbroker/c16c4f3338cd9cc3966e7777d01ce503 to your computer and use it in GitHub Desktop.
Example for splitting a slice of any type into batches with predefined sizes. The size of the last slice will be adjustes to the left over elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func SplitIntoBatches[T any](slice []T, batchSize int) [][]T { | |
var batches = make([][]T, 0) | |
var limit = len(slice) - 1 | |
for i := 0; i < len(slice); i += batchSize { | |
var start = i | |
var end = i + batchSize | |
if end > limit { | |
batches = append(batches, slice[start:limit+1]) | |
} else { | |
batches = append(batches, slice[start:end]) | |
} | |
} | |
return batches | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment