From 531ece860a1797c893baddb6e8536aac4017776e Mon Sep 17 00:00:00 2001 From: Diego Henrique Oliveira Date: Wed, 10 Apr 2024 13:42:46 -0300 Subject: [PATCH] Solve vars with the current value before solve it with all data --- jsonlogic.go | 12 +++++++----- jsonlogic_test.go | 45 ++++++++++++++++++++++++++++++++++++++++++--- vars.go | 6 +----- 3 files changed, 50 insertions(+), 13 deletions(-) diff --git a/jsonlogic.go b/jsonlogic.go index c212312..704cbf5 100644 --- a/jsonlogic.go +++ b/jsonlogic.go @@ -7,8 +7,6 @@ import ( "sort" "strings" - // "runtime/debug" - "github.com/barkimedes/go-deepcopy" ) @@ -422,10 +420,14 @@ func some(values, data interface{}) interface{} { return false } - conditions := solveVars(parsed[1], data) - for _, value := range subject.([]interface{}) { - v := apply(conditions, value) + v := apply( + solveVars( + solveVars(parsed[1], value), + data, + ), + value, + ) if isTrue(v) { return true diff --git a/jsonlogic_test.go b/jsonlogic_test.go index e7516fe..feefb9c 100644 --- a/jsonlogic_test.go +++ b/jsonlogic_test.go @@ -8,9 +8,8 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/diegoholiveira/jsonlogic/v3/internal" + "github.com/stretchr/testify/assert" ) func TestRulesFromJsonLogic(t *testing.T) { @@ -281,13 +280,14 @@ func TestAllWithLists(t *testing.T) { assert.JSONEq(t, "true", result.String()) } + func TestAllWithArrayOfMapData(t *testing.T) { data := strings.NewReader(`[ { "P1": "A", "P2":"a" }, - + { "P1": "B", "P2":"b" @@ -308,6 +308,7 @@ func TestAllWithArrayOfMapData(t *testing.T) { } assert.JSONEq(t, "true", result.String()) } + func TestNoneWithLists(t *testing.T) { rule := strings.NewReader(`{ "none": [ @@ -868,3 +869,41 @@ func TestJsonLogicWithSolvedVars(t *testing.T) { assert.JSONEq(t, expected, string(output)) } + +func TestIssue79(t *testing.T) { + rule := strings.NewReader( + `{"and": [ + {"in": [ + {"var": "flow"}, + ["BRAND"] + ]}, + {"or": [ + {"if": [ + {"missing": ["gender"]}, + true, + false + ]}, + {"some": [ + {"var": "gender"}, + {"==": [ + {"var": null}, + "men" + ]} + ]} + ]} + ]}`, + ) + + data := strings.NewReader(`{"category":["sneakers"],"flow":"BRAND","gender":["men"],"market":"US"}`) + + var result bytes.Buffer + + err := Apply(rule, data, &result) + + if err != nil { + t.Fatal(err) + } + + expected := `true` + assert.JSONEq(t, expected, result.String()) +} diff --git a/vars.go b/vars.go index 3558899..b375eb9 100644 --- a/vars.go +++ b/vars.go @@ -45,11 +45,7 @@ func solveVars(values, data interface{}) interface{} { } func getVar(value, data interface{}) interface{} { - if value == nil { - return data - } - - if isString(value) && toString(value) == "" { + if value == nil || (isString(value) && toString(value) == "") { return data }