Generic map and filter slice helpers
Go
package main
import "fmt"
// Map applies fn to every item and returns a new slice of results.
func Map[T, R any](items []T, fn func(T) R) []R {
out := make([]R, 0, len(items))
for _, item := range items {
out = append(out, fn(item))
}
return out
}
// Filter keeps the items for which keep returns true.
func Filter[T any](items []T, keep func(T) bool) []T {
out := make([]T, 0, len(items))
for _, item := range items {
if keep(item) {
out = append(out, item)
}
}
return out
}
func main() {
numbers := []int{1, 2, 3, 4, 5, 6}
squares := Map(Filter(numbers, func(n int) bool { return n%2 == 0 }), func(n int) int { return n * n })
fmt.Println(squares) // [4 16 36]
}