feat(utils):增加一些常用的函数式功能。
This commit is contained in:
parent
6e9779bd93
commit
3c61cd9e82
27
utils/functional.go
Normal file
27
utils/functional.go
Normal 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
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user