From ac2ecceaec11c6241b529a5414d0b3ec4d0c24ec Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 3 Jan 2024 10:46:28 +0800 Subject: [PATCH] refactor: refact reduce function --- fileutil/testdata/text.txt | 0 slice/slice.go | 17 +++++------------ 2 files changed, 5 insertions(+), 12 deletions(-) delete mode 100644 fileutil/testdata/text.txt diff --git a/fileutil/testdata/text.txt b/fileutil/testdata/text.txt deleted file mode 100644 index e69de29..0000000 diff --git a/slice/slice.go b/slice/slice.go index fbae883..6ac0a15 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -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. // Play: https://go.dev/play/p/_RfXJJWIsIm func Reduce[T any](slice []T, iteratee func(index int, item1, item2 T) T, initial T) T { - if len(slice) == 0 { - return initial + accumulator := initial + + for i, v := range slice { + accumulator = iteratee(i, v, accumulator) } - result := iteratee(0, initial, slice[0]) - - 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 + return accumulator } // ReduceBy produces a value from slice by accumulating the result of each element as passed through the reducer function.