misc: Add FilterMapSlice util

For the scenarios where both `Filter` and `Map` are being applied,
having this util should be faster, as it avoids the creation of an extra
slice during the intermediate step.
This commit is contained in:
Michael Manganiello
2024-03-17 13:44:17 -03:00
parent 3d61659d07
commit 0c17ac3f8d
2 changed files with 17 additions and 10 deletions
+13
View File
@@ -31,6 +31,19 @@ func MapSlice[T any, U any](ts []T, f func(T) U) []U {
return result
}
func FilterMapSlice[T any, U any](ts []T, f func(T) (U, bool)) []U {
if ts == nil {
return nil
}
result := make([]U, 0)
for _, t := range ts {
if u, ok := f(t); ok {
result = append(result, u)
}
}
return result
}
func Reversed[T any](ts []T) []T {
if ts == nil {
return nil