feat(utils):增加一些常用的函数式功能。

This commit is contained in:
徐涛 2022-08-15 09:23:19 +08:00
parent 6e9779bd93
commit 3c61cd9e82

27
utils/functional.go Normal file
View File

@ -0,0 +1,27 @@
package utils
func Map[S, T any](source []S, f func(S) T) []T {
dest := make([]T, len(source))
for i, elem := range source {
dest[i] = f(elem)
}
return dest
}
func Reduce[S, T any](source []S, initialValue T, f func(T, S) T) T {
acc := initialValue
for _, elem := range source {
acc = f(acc, elem)
}
return acc
}
func Filter[T any](source []T, f func(T) bool) []T {
var dest []T
for _, elem := range source {
if f(elem) {
dest = append(dest, elem)
}
}
return dest
}