github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/walk/api.go (about) 1 // Package walk provides utilily functions for the interface Walker 2 package walk 3 4 import ( 5 "github.com/m4gshm/gollections/c" 6 ) 7 8 // Group groups elements by keys into a map 9 func Group[T any, K comparable, W c.ForEach[T]](elements W, by func(T) K) map[K][]T { 10 groups := map[K][]T{} 11 elements.ForEach(func(e T) { 12 key := by(e) 13 group := groups[key] 14 if group == nil { 15 group = make([]T, 0) 16 } 17 groups[key] = append(group, e) 18 }) 19 return groups 20 }