fixedpoint: add reducer and its tests

This commit is contained in:
c9s 2022-09-07 14:00:26 +08:00
parent e161f4ec1a
commit 668180f8aa
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
3 changed files with 13 additions and 4 deletions

View File

@ -2,7 +2,16 @@ package fixedpoint
type Reducer func(prev, curr Value) Value
func Reduce(values []Value, init Value, reducer Reducer) Value {
func SumReducer(prev, curr Value) Value {
return prev.Add(curr)
}
func Reduce(values []Value, reducer Reducer, a ...Value) Value {
init := Zero
if len(a) > 0 {
init = a[0]
}
if len(values) == 0 {
return init
}

View File

@ -31,7 +31,7 @@ func TestReduce(t *testing.T) {
}
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)
assert.Equalf(t, tt.want, Reduce(tt.args.values, tt.args.reducer, tt.args.init), "Reduce(%v, %v, %v)", tt.args.values, tt.args.init, tt.args.reducer)
})
}
}

View File

@ -2,8 +2,8 @@ package fixedpoint
type Slice []Value
func (s Slice) Reduce(init Value, reducer Reducer) Value {
return Reduce(s, init, reducer)
func (s Slice) Reduce(reducer Reducer, a ...Value) Value {
return Reduce(s, reducer, a...)
}
// Defaults to ascending sort