mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-21 22:43:52 +00:00
fixedpoint: add reducer
This commit is contained in:
parent
6b4661783d
commit
e0e279f756
16
pkg/fixedpoint/reduce.go
Normal file
16
pkg/fixedpoint/reduce.go
Normal 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
|
||||
}
|
37
pkg/fixedpoint/reduce_test.go
Normal file
37
pkg/fixedpoint/reduce_test.go
Normal 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
7
pkg/fixedpoint/slice.go
Normal file
|
@ -0,0 +1,7 @@
|
|||
package fixedpoint
|
||||
|
||||
type Slice []Value
|
||||
|
||||
func (s Slice) Reduce(init Value, reducer Reducer) Value {
|
||||
return Reduce(s, init, reducer)
|
||||
}
|
Loading…
Reference in New Issue
Block a user