-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice_loop.go
More file actions
33 lines (32 loc) · 911 Bytes
/
Copy pathslice_loop.go
File metadata and controls
33 lines (32 loc) · 911 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package gofu
// MapChunks splits s into chunks, calls fn on each, and collects the results. [ Immutable ] [ time: O(n); space: O(n)]
//
// Chunks are distributed so the size difference between any two chunks is at most one element.
// See ForEachChunk for the exact distribution algorithm.
//
// Example:
//
// gofu.Slice([]int{1, 2, 3, 4, 5, 6, 7}).
// MapChunks(3, func(i int, chunk gofu.Slice[int]) string { return fmt.Sprint(chunk) })
// // []string{"[1 2 3]", "[4 5 6]", "[7]"}
func (s Slice[T]) MapChunks[R any](chunks int, fn func(int, Slice[T]) R) []R {
if len(s) == 0 || chunks <= 1 {
return []R{fn(0, s)}
}
if chunks > len(s) {
chunks = len(s)
}
results := make([]R, chunks)
size := len(s) / chunks
rem := len(s) % chunks
start := 0
for i := 0; i < chunks; i++ {
end := start + size
if i < rem {
end++
}
results[i] = fn(i, s[start:end])
start = end
}
return results
}