Skip to content

Instantly share code, notes, and snippets.

@whynotavailable
Created August 27, 2024 10:35
Show Gist options
  • Save whynotavailable/95728a593c65a04773ee498312fc2f7c to your computer and use it in GitHub Desktop.
Save whynotavailable/95728a593c65a04773ee498312fc2f7c to your computer and use it in GitHub Desktop.
Functions for slice transformations in go
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