Skip to content

Instantly share code, notes, and snippets.

@kkroesch
Created March 27, 2024 20:40
Show Gist options
  • Save kkroesch/4d8b1579ce7cf0ae17a3e092a0c8dbcc to your computer and use it in GitHub Desktop.
Save kkroesch/4d8b1579ce7cf0ae17a3e092a0c8dbcc to your computer and use it in GitHub Desktop.
Map, Reduce, Filter with Go Generics
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