1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 22:22:29 +08:00

feat: add GroupWith func

This commit is contained in:
dudaodong
2022-03-21 15:29:10 +08:00
parent 3ae4a35d04
commit 50ef63e27d
2 changed files with 34 additions and 0 deletions

View File

@@ -253,6 +253,25 @@ func GroupBy[T any](slice []T, groupFn func(index int, t T) bool) ([]T, []T) {
return groupA, groupB
}
// GroupWith return a map composed of keys generated from the results of running each element of slice thru iteratee.
func GroupWith[T any, U comparable](slice []T, iteratee func(T) U) map[U][]T {
if iteratee == nil {
panic("iteratee func is missing")
}
res := make(map[U][]T)
for _, v := range slice {
key := iteratee(v)
if _, ok := res[key]; !ok {
res[key] = []T{}
}
res[key] = append(res[key], v)
}
return res
}
// Find iterates over elements of slice, returning the first one that passes a truth test on predicate function.
// If return T is nil then no items matched the predicate func
func Find[T any](slice []T, predicate func(index int, t T) bool) (*T, bool) {