Skip to content

Commit

Permalink
Use the first value when min / max
Browse files Browse the repository at this point in the history
  • Loading branch information
Diego Henrique Oliveira committed Oct 16, 2023
1 parent 43283eb commit 287d0ea
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 7 deletions.
25 changes: 18 additions & 7 deletions jsonlogic.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"encoding/json"
"fmt"
"io"
"math"
"sort"
"strings"

Expand Down Expand Up @@ -195,10 +194,16 @@ func _in(value interface{}, values interface{}) bool {
}

func max(values interface{}) interface{} {
bigger := math.SmallestNonzeroFloat64
converted := values.([]interface{})
size := len(converted)
if size == 0 {
return nil
}

bigger := toNumber(converted[0])

for _, n := range values.([]interface{}) {
_n := toNumber(n)
for i := 1; i < size; i++ {
_n := toNumber(converted[i])
if _n > bigger {
bigger = _n
}
Expand All @@ -208,10 +213,16 @@ func max(values interface{}) interface{} {
}

func min(values interface{}) interface{} {
smallest := math.MaxFloat64
converted := values.([]interface{})
size := len(converted)
if size == 0 {
return nil
}

smallest := toNumber(converted[0])

for _, n := range values.([]interface{}) {
_n := toNumber(n)
for i := 1; i < size; i++ {
_n := toNumber(converted[i])
if smallest > _n {
smallest = _n
}
Expand Down
42 changes: 42 additions & 0 deletions jsonlogic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,48 @@ func TestIssue58_example(t *testing.T) {
assert.JSONEq(t, expected, result.String())
}

func TestIssue71_example_empty_min(t *testing.T) {
data := strings.NewReader(`{}`)
logic := strings.NewReader(`{"min":[]}`)

var result bytes.Buffer
err := Apply(logic, data, &result)
if err != nil {
t.Fatal(err)
}

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

func TestIssue71_example_empty_max(t *testing.T) {
data := strings.NewReader(`{}`)
logic := strings.NewReader(`{"max":[]}`)

var result bytes.Buffer
err := Apply(logic, data, &result)
if err != nil {
t.Fatal(err)
}

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

func TestIssue71_example_max(t *testing.T) {
data := strings.NewReader(`{}`)
logic := strings.NewReader(`{"max":[-3, -2]}`)

var result bytes.Buffer
err := Apply(logic, data, &result)
if err != nil {
t.Fatal(err)
}

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

func TestJsonLogicWithSolvedVars(t *testing.T) {
rule := json.RawMessage(`{
"or":[
Expand Down

0 comments on commit 287d0ea

Please sign in to comment.