mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
Fixes useless capacity hint of 0 for map initialization. Uses estimated capacity of len(values)/10 to reduce map resizing operations. Changes: - Before: make(map[K][]V, 0) - capacity 0 is meaningless for maps - After: make(map[K][]V, len(values)/10) - reasonable estimate Impact: - Reduces map resizing overhead during population - Assumes ~10% unique keys (reasonable for grouping operations) - May over-allocate for high cardinality, but acceptable trade-off This is a minor optimization that avoids repeated map growth when keys are added. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
15 lines
365 B
Go
15 lines
365 B
Go
package underscore
|
|
|
|
// GroupBy splits a slice into a map[K][]V grouped by the result of the iterator function.
|
|
func GroupBy[K comparable, V any](values []V, f func(V) K) map[K][]V {
|
|
res := make(map[K][]V, len(values)/10)
|
|
for _, v := range values {
|
|
k := f(v)
|
|
if r, ok := res[k]; ok {
|
|
res[k] = append(r, v)
|
|
} else {
|
|
res[k] = []V{v}
|
|
}
|
|
}
|
|
return res
|
|
}
|