Skip to content

Commit

Permalink
Merge pull request #97 from /issues/96
Browse files Browse the repository at this point in the history
Ensure empty slices have the same behavior as empty strings
  • Loading branch information
diegoholiveira authored Jan 12, 2025
2 parents 1dafb58 + e8f3017 commit 40cb81b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
14 changes: 14 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,20 @@ func isSlice(obj any) bool {
return is(obj, reflect.Slice)
}

func isEmptySlice(obj any) bool {
if !isSlice(obj) {
return false
}

for _, v := range obj.([]any) {
if isTrue(v) {
return false
}
}

return true
}

func isTrue(obj any) bool {
if isBool(obj) {
return obj.(bool)
Expand Down
20 changes: 19 additions & 1 deletion issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,29 @@ func TestIssue81(t *testing.T) {
var result bytes.Buffer

err := jsonlogic.Apply(strings.NewReader(rule), strings.NewReader(data), &result)

if err != nil {
t.Fatal(err)
}

expected := `true`
assert.JSONEq(t, expected, result.String())
}

func TestIssue96(t *testing.T) {
rule := `{"map":[
{"var":"integers"},
{"*":[{"var":[""]},2]}
]}`

data := `{"integers": [1,2,3]}`

var result bytes.Buffer

err := jsonlogic.Apply(strings.NewReader(rule), strings.NewReader(data), &result)
if err != nil {
t.Fatal(err)
}

expected := `[2, 4, 6]`
assert.JSONEq(t, expected, result.String())
}
5 changes: 5 additions & 0 deletions vars.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ func solveVars(values, data any) any {
continue
}

if isEmptySlice(value) {
logic["var"] = ""
continue
}

val := getVar(value, data)
if val != nil {
return val
Expand Down

0 comments on commit 40cb81b

Please sign in to comment.