fixedpoint: add reducer

This commit is contained in:
c9s 2022-09-07 12:28:13 +08:00
parent 6b4661783d
commit e0e279f756
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
3 changed files with 60 additions and 0 deletions

16
pkg/fixedpoint/reduce.go Normal file
View File

@ -0,0 +1,16 @@
package fixedpoint
type Reducer func(prev, curr Value) Value
func Reduce(values []Value, init Value, reducer Reducer) Value {
if len(values) == 0 {
return init
}
r := reducer(init, values[0])
for i := 1; i < len(values); i++ {
r = reducer(r, values[i])
}
return r
}

View File

@ -0,0 +1,37 @@
package fixedpoint
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestReduce(t *testing.T) {
type args struct {
values []Value
init Value
reducer Reducer
}
tests := []struct {
name string
args args
want Value
}{
{
name: "simple",
args: args{
values: []Value{NewFromFloat(1), NewFromFloat(2), NewFromFloat(3)},
init: NewFromFloat(0.0),
reducer: func(prev, curr Value) Value {
return prev.Add(curr)
},
},
want: NewFromFloat(6),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, Reduce(tt.args.values, tt.args.init, tt.args.reducer), "Reduce(%v, %v, %v)", tt.args.values, tt.args.init, tt.args.reducer)
})
}
}

7
pkg/fixedpoint/slice.go Normal file
View File

@ -0,0 +1,7 @@
package fixedpoint
type Slice []Value
func (s Slice) Reduce(init Value, reducer Reducer) Value {
return Reduce(s, init, reducer)
}