package core

// Chunk splits xs into sub-slices of the given size.
// The last chunk may contain fewer than size elements.
// Returns nil if xs is empty. Panics if size <= 0.
func Chunk[T any](xs []T, size int) [][]T {
	if size <= 0 {
		panic("chunk size must be > 0")
	}
	n := len(xs)
	if n == 0 {
		return nil
	}

	numChunks := (n + size - 1) / size
	chunks := make([][]T, 0, numChunks)
	for i := 0; i < n; i += size {
		end := i + size
		if end > n {
			end = n
		}
		chunks = append(chunks, xs[i:end])
	}
	return chunks
}
