fixedpoint: add sort interface support on fixedpoint

This commit is contained in:
c9s 2022-09-07 12:35:09 +08:00
parent e0e279f756
commit e161f4ec1a
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 52 additions and 0 deletions

View File

@ -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 }

View File

@ -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())
}