Created
August 27, 2024 10:35
-
-
Save whynotavailable/95728a593c65a04773ee498312fc2f7c to your computer and use it in GitHub Desktop.
Functions for slice transformations in go
This file contains hidden or 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 Reduce[TAcc any, T any](list []T, reducer func(TAcc, T) TAcc, init TAcc) TAcc { | |
acc := init | |
for _, t := range list { | |
acc = reducer(acc, t) | |
} | |
return acc | |
} | |
func Map[T any, TRet any](list []T, mapper func(T) TRet) []TRet { | |
n := make([]TRet, len(list)) | |
for i, iter := range list { | |
n[i] = mapper(iter) | |
} | |
return n | |
} | |
func Filter[T any](list []T, filter func(t T) bool) []T { | |
// Set the capacity to the max and trim it down later. | |
n := make([]T, 0, len(list)) | |
for _, iter := range list { | |
if filter(iter) { | |
n = append(n, iter) | |
} | |
} | |
return slices.Clip(n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment