From f166829fe46b8a2c98a5fbe1e97ffe4ac7ad9b13 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Tue, 2 Jan 2024 17:16:56 -0800 Subject: [PATCH] fn: add reduce func --- fn/func.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 fn/func.go diff --git a/fn/func.go b/fn/func.go new file mode 100644 index 000000000..056f84aef --- /dev/null +++ b/fn/func.go @@ -0,0 +1,17 @@ +package fn + +// Reducer represents a function that takes an accumulator and the value, then +// returns a new accumulator. +type Reducer[T, V any] func(accum T, value V) T + +// Reduce takes a slice of something, and a reducer, and produces a final +// accumulated value. +func Reduce[T any, V any, S []V](s S, f Reducer[T, V]) T { + var accum T + + for _, x := range s { + accum = f(accum, x) + } + + return accum +}