Added FilterMap
This commit is contained in:
parent
f7abe7c01f
commit
e33476ea5c
2 changed files with 42 additions and 1 deletions
|
|
@ -16,3 +16,22 @@ func Filter[T any](ts []T, predicate func(t T) bool) []T {
|
|||
}
|
||||
return filteredTs
|
||||
}
|
||||
|
||||
// FilterMap returns a mapped slice containing all the elements of ts for which the passed in
|
||||
// predicate returns true. If no items match the predicate, the function will return
|
||||
// an empty slice. If ts is nil, the function will also return nil.
|
||||
func FilterMap[T, U any](ts []T, predicate func(t T) (U, bool)) []U {
|
||||
if ts == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
filteredUs := make([]U, 0)
|
||||
for _, t := range ts {
|
||||
u, ok := predicate(t)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
filteredUs = append(filteredUs, u)
|
||||
}
|
||||
return filteredUs
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue