Skip to content

Commit

Permalink
tpl/collections: Convert numeric values to float64 and compare them
Browse files Browse the repository at this point in the history
Fixes #5685
  • Loading branch information
tryzniak authored and bep committed May 30, 2019
1 parent 4c56002 commit fb007e9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions tpl/collections/where.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,17 @@ func (ns *Namespace) checkCondition(v, mv reflect.Value, op string) (bool, error
slv = v.Interface()
slmv = mv.Interface()
}
} else if isNumber(v.Kind()) && isNumber(mv.Kind()) {
fv, err := toFloat(v)
if err != nil {
return false, err
}
fvp = &fv
fmv, err := toFloat(mv)
if err != nil {
return false, err
}
fmvp = &fmv
} else {
if mv.Kind() != reflect.Array && mv.Kind() != reflect.Slice {
return false, nil
Expand Down Expand Up @@ -426,6 +437,8 @@ func toFloat(v reflect.Value) (float64, error) {
switch v.Kind() {
case reflect.Float32, reflect.Float64:
return v.Float(), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Convert(reflect.TypeOf(float64(0))).Float(), nil
case reflect.Interface:
return toFloat(v.Elem())
}
Expand Down
21 changes: 21 additions & 0 deletions tpl/collections/where_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,27 @@ func TestWhere(t *testing.T) {
key: "b", match: 4.0, op: "<",
expect: []map[string]float64{{"a": 1, "b": 2}},
},
{
seq: []map[string]float64{
{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4},
},
key: "b", match: 4, op: "<",
expect: []map[string]float64{{"a": 1, "b": 2}},
},
{
seq: []map[string]int{
{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4},
},
key: "b", match: 4.0, op: "<",
expect: []map[string]int{{"a": 1, "b": 2}},
},
{
seq: []map[string]int{
{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4},
},
key: "b", match: 4.2, op: "<",
expect: []map[string]int{{"a": 1, "b": 2}, {"a": 3, "b": 4}},
},
{
seq: []map[string]float64{
{"a": 1, "b": 2}, {"a": 3, "b": 4}, {"a": 5, "x": 4},
Expand Down

0 comments on commit fb007e9

Please sign in to comment.