Skip to content

Commit

Permalink
Add support for float in sort() builtin
Browse files Browse the repository at this point in the history
Fixes #448
  • Loading branch information
antonmedv committed Nov 16, 2023
1 parent 507d734 commit d27e5a3
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
7 changes: 5 additions & 2 deletions builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import (
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/antonmedv/expr"
"github.com/antonmedv/expr/builtin"
"github.com/antonmedv/expr/checker"
"github.com/antonmedv/expr/conf"
"github.com/antonmedv/expr/parser"
"github.com/antonmedv/expr/test/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestBuiltin(t *testing.T) {
Expand Down Expand Up @@ -403,6 +404,7 @@ func TestBuiltin_sort(t *testing.T) {
env := map[string]any{
"ArrayOfString": []string{"foo", "bar", "baz"},
"ArrayOfInt": []int{3, 2, 1},
"ArrayOfFloat": []float64{3.0, 2.0, 1.0},
"ArrayOfFoo": []mock.Foo{{Value: "c"}, {Value: "a"}, {Value: "b"}},
}
tests := []struct {
Expand All @@ -411,6 +413,7 @@ func TestBuiltin_sort(t *testing.T) {
}{
{`sort([])`, []any{}},
{`sort(ArrayOfInt)`, []any{1, 2, 3}},
{`sort(ArrayOfFloat)`, []any{1.0, 2.0, 3.0}},
{`sort(ArrayOfInt, 'desc')`, []any{3, 2, 1}},
{`sortBy(ArrayOfFoo, 'Value')`, []any{mock.Foo{Value: "a"}, mock.Foo{Value: "b"}, mock.Foo{Value: "c"}}},
{`sortBy([{id: "a"}, {id: "b"}], "id", "desc")`, []any{map[string]any{"id": "b"}, map[string]any{"id": "a"}}},
Expand Down
5 changes: 5 additions & 0 deletions builtin/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ func (s *Sortable) Less(i, j int) bool {
return a.Int() > b.Int()
}
return a.Int() < b.Int()
case reflect.Float64, reflect.Float32:
if s.Desc {
return a.Float() > b.Float()
}
return a.Float() < b.Float()
case reflect.String:
if s.Desc {
return a.String() > b.String()
Expand Down

0 comments on commit d27e5a3

Please sign in to comment.