1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

refactor: refact reduce function

This commit is contained in:
dudaodong
2024-01-03 10:46:28 +08:00
parent a06bb8ee6a
commit ac2ecceaec
2 changed files with 5 additions and 12 deletions

View File

View File

@@ -498,20 +498,13 @@ func FlatMap[T any, U any](slice []T, iteratee func(index int, item T) []U) []U
// Reduce creates an slice of values by running each element of slice thru iteratee function. // Reduce creates an slice of values by running each element of slice thru iteratee function.
// Play: https://go.dev/play/p/_RfXJJWIsIm // Play: https://go.dev/play/p/_RfXJJWIsIm
func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T { func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T {
if len(slice) == 0 { accumulator := initial
return initial
for i, v := range slice {
accumulator = iteratee(i, v, accumulator)
} }
result := iteratee(0, initial, slice[0]) return accumulator
tmp := make([]T, 2)
for i := 1; i < len(slice); i++ {
tmp[0] = result
tmp[1] = slice[i]
result = iteratee(i, tmp[0], tmp[1])
}
return result
} }
// ReduceBy produces a value from slice by accumulating the result of each element as passed through the reducer function. // ReduceBy produces a value from slice by accumulating the result of each element as passed through the reducer function.