Skip to content

Commit

Permalink
Fix where with different types
Browse files Browse the repository at this point in the history
  • Loading branch information
reindert-vetter committed Dec 22, 2022
1 parent 7996a30 commit 9e38fa6
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
25 changes: 21 additions & 4 deletions support/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package support

import (
"github.com/confetti-framework/errors"
"reflect"
"github.com/spf13/cast"
"reflect"
"strconv"
)

Expand Down Expand Up @@ -183,12 +184,28 @@ func (c Collection) Empty() bool {
}

func (c Collection) Where(key string, operator string, expected interface{}) Collection {
result, err := c.WhereE(key, operator, expected)
if err != nil {
panic(err)
}
return result
}

func (c Collection) WhereE(key string, operator string, expected interface{}) (Collection, error) {
result := NewCollection()
var err error
for _, item := range c {
compareValue := item.Get(key).Raw()
if compareValue == expected {
compareValue, err := cast.ToStringE(item.Get(key).Raw())
if err != nil {
err = errors.New("can't compare values to handle the Where(E) method, because we need to cast compare value to string")
}
expectedValue, err := cast.ToStringE(cast.ToString(expected))
if err != nil {
err = errors.New("can't compare values to handle the Where(E) method, because we need to cast expected value to string")
}
if compareValue == expectedValue {
result = result.Push(item)
}
}
return result
return result, err
}
16 changes: 14 additions & 2 deletions support/test/collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func Test_collection_not_empty(t *testing.T) {
}

func Test_collection_where_slice_has_value(t *testing.T) {
data := support.NewCollection([]map[string]interface{}{
data := support.NewCollection([]map[string]interface{}{
{
"color": "blue",
},
Expand All @@ -217,7 +217,19 @@ func Test_collection_where_slice_has_value(t *testing.T) {

result := data.Where("color", "=", "blue")

require.Equal(t, 1, len(result))
require.Equal(t, 1, len(result))
}

func Test_collection_where_slice_has_other_integer(t *testing.T) {
data := support.NewCollection([]map[string]interface{}{
{
"age": int64(5),
},
})

result := data.Where("age", "=", int(5))

require.Equal(t, 1, len(result))
}

var emptyInterface interface{}

0 comments on commit 9e38fa6

Please sign in to comment.