Created
February 8, 2023 08:05
-
-
Save raimohanska/a6572d0ceb585e7cdbc87fdc362100bd to your computer and use it in GitHub Desktop.
Golang FP basics: filter, map, flatMap
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
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