Created
June 25, 2022 11:29
-
-
Save ObiajuluM/e603d661d299d4fc403e2df9979d3d84 to your computer and use it in GitHub Desktop.
Handy snippets for generating common list comprehension function implementaions for your type(s) in golang
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
// Replace "X" and "Y" with your desired types | |
func mapXtoY(collection []X, fn func(elem X) Y) []Y { | |
var result []Y | |
for _, item := range collection { | |
result = append(result, fn(item)) | |
} | |
return result | |
} | |
func reduceXtoY(collection []X, init Y, fn func(memo Y, elem X) Y) Y { | |
result := init | |
for _, item := range collection { | |
result = fn(result, item) | |
} | |
return result | |
} | |
func filterXs(collection []X, fn func(elem X) bool) []X { | |
var result []X | |
for _, item := range collection { | |
if fn(item) { | |
result = append(result, item) | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment