Created
March 27, 2024 20:40
-
-
Save kkroesch/4d8b1579ce7cf0ae17a3e092a0c8dbcc to your computer and use it in GitHub Desktop.
Map, Reduce, Filter with Go Generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package functional | |
func Map[TValue any](values []TValue, f func(TValue) TValue) { | |
for i, value := range values { | |
values[i] = f(value) | |
} | |
} | |
func Reduce[TValue, TResult any](values []TValue, f func(TValue, TResult) TResult) TResult { | |
var result TResult | |
for _, value := range values { | |
result = f(value, result) | |
} | |
return result | |
} | |
func Filter[TValue any](values []TValue, f func(TValue) bool) []TValue { | |
filtered_values := make([]TValue, 0) | |
for _, value := range values { | |
if f(value) { | |
filtered_values = append(filtered_values, value) | |
} | |
} | |
return filtered_values | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment