diff --git a/support/collection.go b/support/collection.go index a9d2b2d..a9aac0d 100644 --- a/support/collection.go +++ b/support/collection.go @@ -2,7 +2,8 @@ package support import ( "github.com/confetti-framework/errors" - "reflect" + "github.com/spf13/cast" + "reflect" "strconv" ) @@ -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 } diff --git a/support/test/collection_test.go b/support/test/collection_test.go index 2d50162..01a63f7 100644 --- a/support/test/collection_test.go +++ b/support/test/collection_test.go @@ -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", }, @@ -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{}