From e0e279f756ab2a21121056575dee24bb0d58d3c9 Mon Sep 17 00:00:00 2001 From: c9s Date: Wed, 7 Sep 2022 12:28:13 +0800 Subject: [PATCH] fixedpoint: add reducer --- pkg/fixedpoint/reduce.go | 16 +++++++++++++++ pkg/fixedpoint/reduce_test.go | 37 +++++++++++++++++++++++++++++++++++ pkg/fixedpoint/slice.go | 7 +++++++ 3 files changed, 60 insertions(+) create mode 100644 pkg/fixedpoint/reduce.go create mode 100644 pkg/fixedpoint/reduce_test.go create mode 100644 pkg/fixedpoint/slice.go diff --git a/pkg/fixedpoint/reduce.go b/pkg/fixedpoint/reduce.go new file mode 100644 index 000000000..fc8db575c --- /dev/null +++ b/pkg/fixedpoint/reduce.go @@ -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 +} diff --git a/pkg/fixedpoint/reduce_test.go b/pkg/fixedpoint/reduce_test.go new file mode 100644 index 000000000..704e1d590 --- /dev/null +++ b/pkg/fixedpoint/reduce_test.go @@ -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) + }) + } +} diff --git a/pkg/fixedpoint/slice.go b/pkg/fixedpoint/slice.go new file mode 100644 index 000000000..8b0ccffc6 --- /dev/null +++ b/pkg/fixedpoint/slice.go @@ -0,0 +1,7 @@ +package fixedpoint + +type Slice []Value + +func (s Slice) Reduce(init Value, reducer Reducer) Value { + return Reduce(s, init, reducer) +}