From e161f4ec1a5072c266965145eef77c266da04660 Mon Sep 17 00:00:00 2001 From: c9s Date: Wed, 7 Sep 2022 12:35:09 +0800 Subject: [PATCH] fixedpoint: add sort interface support on fixedpoint --- pkg/fixedpoint/slice.go | 17 +++++++++++++++++ pkg/fixedpoint/slice_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 pkg/fixedpoint/slice_test.go diff --git a/pkg/fixedpoint/slice.go b/pkg/fixedpoint/slice.go index 8b0ccffc6..a59542787 100644 --- a/pkg/fixedpoint/slice.go +++ b/pkg/fixedpoint/slice.go @@ -5,3 +5,20 @@ type Slice []Value func (s Slice) Reduce(init Value, reducer Reducer) Value { return Reduce(s, init, reducer) } + +// Defaults to ascending sort +func (s Slice) Len() int { return len(s) } +func (s Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s Slice) Less(i, j int) bool { return s[i].Compare(s[j]) < 0 } + +type Ascending []Value + +func (s Ascending) Len() int { return len(s) } +func (s Ascending) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s Ascending) Less(i, j int) bool { return s[i].Compare(s[j]) < 0 } + +type Descending []Value + +func (s Descending) Len() int { return len(s) } +func (s Descending) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s Descending) Less(i, j int) bool { return s[i].Compare(s[j]) > 0 } diff --git a/pkg/fixedpoint/slice_test.go b/pkg/fixedpoint/slice_test.go new file mode 100644 index 000000000..082db9079 --- /dev/null +++ b/pkg/fixedpoint/slice_test.go @@ -0,0 +1,35 @@ +package fixedpoint + +import ( + "sort" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSortInterface(t *testing.T) { + slice := Slice{ + NewFromInt(7), + NewFromInt(3), + NewFromInt(1), + NewFromInt(2), + NewFromInt(5), + } + sort.Sort(slice) + assert.Equal(t, "1", slice[0].String()) + assert.Equal(t, "2", slice[1].String()) + assert.Equal(t, "3", slice[2].String()) + assert.Equal(t, "5", slice[3].String()) + + sort.Sort(Descending(slice)) + assert.Equal(t, "7", slice[0].String()) + assert.Equal(t, "5", slice[1].String()) + assert.Equal(t, "3", slice[2].String()) + assert.Equal(t, "2", slice[3].String()) + + sort.Sort(Ascending(slice)) + assert.Equal(t, "1", slice[0].String()) + assert.Equal(t, "2", slice[1].String()) + assert.Equal(t, "3", slice[2].String()) + assert.Equal(t, "5", slice[3].String()) +}