Skip to content

Commit

Permalink
Allow the reduce function work with string values (#54)
Browse files Browse the repository at this point in the history
* Added test array with string

* Allow the reduce function work with string values

* Update unsupported type for reduce

Co-authored-by: Juliano Galgaro <[email protected]>
  • Loading branch information
julianogalgaro and julianofgalgaro authored Jul 21, 2022
1 parent b3253f2 commit d34d6a7
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions arrays.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ func reduce(values, data interface{}) interface{} {
} else if isNumber(parsed[2]) {
accumulator = toNumber(parsed[2])
valueType = "number"
} else if isString(parsed[2]) {
accumulator = toString(parsed[2])
valueType = "string"
} else {
panic(ErrReduceDataType{
dataType: fmt.Sprintf("%T", parsed[2]),
Expand Down Expand Up @@ -129,6 +132,8 @@ func reduce(values, data interface{}) interface{} {
context["accumulator"] = isTrue(v)
case "number":
context["accumulator"] = toNumber(v)
case "string":
context["accumulator"] = toString(v)
}
}

Expand Down
21 changes: 21 additions & 0 deletions arrays_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,24 @@ func TestReduceBoolValues(t *testing.T) {

assert.Equal(t, expected, result)
}

func TestReduceStringValues(t *testing.T) {
var parsed interface{}

err := json.Unmarshal([]byte(`[
["a",null,"b"],
{"cat":[{"var":"current"}, {"var":"accumulator"}]},
""
]`), &parsed)
if err != nil {
panic(err)
}

result := reduce(parsed, nil)

var expected interface{}

json.Unmarshal([]byte(`"ba"`), &expected) // nolint:errcheck

assert.Equal(t, expected, result)
}
4 changes: 2 additions & 2 deletions jsonlogic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -593,7 +593,7 @@ func TestReduceFilterAndNotContains(t *testing.T) {
}

func TestReduceWithUnsupportedValue(t *testing.T) {
b := []byte(`{"reduce":[{"filter":[{"var":"data"},{"==":[{"var":""},""]}]},{"cat":[{"var":"current"},{"var":"accumulator"}]},"str"]}`)
b := []byte(`{"reduce":[{"filter":[{"var":"data"},{"==":[{"var":""},""]}]},{"cat":[{"var":"current"},{"var":"accumulator"}]},null]}`)

rule := map[string]interface{}{}
_ = json.Unmarshal(b, &rule)
Expand All @@ -602,7 +602,7 @@ func TestReduceWithUnsupportedValue(t *testing.T) {
}

_, err := ApplyInterface(rule, data)
assert.EqualError(t, err, "The type \"string\" is not supported")
assert.EqualError(t, err, "The type \"<nil>\" is not supported")
}

func TestAddOperator(t *testing.T) {
Expand Down

0 comments on commit d34d6a7

Please sign in to comment.