Skip to content

Commit

Permalink
Solve vars with the current value before solve it with all data (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
Diego Henrique Oliveira authored Apr 10, 2024
1 parent f82ebb4 commit 0926afe
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 13 deletions.
12 changes: 7 additions & 5 deletions jsonlogic.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"sort"
"strings"

// "runtime/debug"

"github.com/barkimedes/go-deepcopy"
)

Expand Down Expand Up @@ -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
Expand Down
45 changes: 42 additions & 3 deletions jsonlogic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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"
Expand All @@ -308,6 +308,7 @@ func TestAllWithArrayOfMapData(t *testing.T) {
}
assert.JSONEq(t, "true", result.String())
}

func TestNoneWithLists(t *testing.T) {
rule := strings.NewReader(`{
"none": [
Expand Down Expand Up @@ -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())
}
6 changes: 1 addition & 5 deletions vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down

0 comments on commit 0926afe

Please sign in to comment.