Skip to content

Instantly share code, notes, and snippets.

@raimohanska
Created February 8, 2023 08:05
Show Gist options
  • Save raimohanska/a6572d0ceb585e7cdbc87fdc362100bd to your computer and use it in GitHub Desktop.
Save raimohanska/a6572d0ceb585e7cdbc87fdc362100bd to your computer and use it in GitHub Desktop.
Golang FP basics: filter, map, flatMap
func Map[A any, B any](things []A, mapper func (x A) B) []B {
result := make([] B, len(things))
for i := range(things) {
result[i] = mapper(things[i])
}
return result
}
func Filter[A any](things []A, predicate func (x A) bool) []A {
result := make([] A, len(things))
count := 0
for i := range(things) {
if predicate(things[i]) {
result[count] = things[i]
count++
}
}
return result[0:count]
}
func FlatMap[A any, B any](things []A, mapper func (x A) []B) []B {
return Flatten(Map(things, mapper))
}
func Flatten[A any](things [][]A) []A {
count := 0
for i := range(things) {
count += len(things[i])
}
result := make([] A, count)
index := 0
for i := range(things) {
for j := range(things[i]) {
result[index] = things[i][j]
index++
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment