Skip to content

Instantly share code, notes, and snippets.

@ObiajuluM
Created June 25, 2022 11:29
Show Gist options
  • Save ObiajuluM/e603d661d299d4fc403e2df9979d3d84 to your computer and use it in GitHub Desktop.
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
// 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