mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
feat: reduce
This commit is contained in:
parent
ad518df993
commit
fa9989c181
2 changed files with 27 additions and 0 deletions
8
reduce.go
Normal file
8
reduce.go
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
package underscore
|
||||
|
||||
func Reduce[T, P any](values []T, predicate func(T, P) P, acc P) P {
|
||||
for _, v := range values {
|
||||
acc = predicate(v, acc)
|
||||
}
|
||||
return acc
|
||||
}
|
||||
19
reduce_test.go
Normal file
19
reduce_test.go
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
package underscore_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
u "github.com/rjNemo/underscore"
|
||||
)
|
||||
|
||||
func TestReduce(t *testing.T) {
|
||||
nums := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||
reducer := func(n, acc int) int {
|
||||
return n + acc
|
||||
}
|
||||
want := 45
|
||||
|
||||
assert.Equal(t, want, u.Reduce(nums, reducer, 0))
|
||||
}
|
||||
Loading…
Reference in a new issue