Skip to content

Commit 96ff938

Browse files
committed
Handles edge cases of + and * the way jsonlogic.com does
When presented with an array parameter, jsonlogic.com uses the first value for + and * expressions.
1 parent dcd6780 commit 96ff938

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/main/java/io/github/jamsesso/jsonlogic/evaluator/expressions/MathExpression.java

+6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.github.jamsesso.jsonlogic.evaluator.expressions;
22

33
import io.github.jamsesso.jsonlogic.evaluator.JsonLogicEvaluationException;
4+
import io.github.jamsesso.jsonlogic.utils.ArrayLike;
45

56
import java.util.List;
67
import java.util.function.BiFunction;
@@ -45,6 +46,11 @@ public Object evaluate(List arguments, Object data, String jsonPath) throws Json
4546
for (int i = 0; i < arguments.size(); i++) {
4647
Object value = arguments.get(i);
4748

49+
if (key.equals("*") || key.equals("+")) {
50+
while (ArrayLike.isEligible(value)) {
51+
value = new ArrayLike(value).get(0);
52+
}
53+
}
4854
if (value instanceof String) {
4955
try {
5056
values[i] = Double.parseDouble((String) value);

src/test/java/io/github/jamsesso/jsonlogic/MathExpressionTests.java

+16
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ public void testSingleAdd() throws JsonLogicException {
3232
assertEquals(3.14, result);
3333
}
3434

35+
@Test
36+
public void testAddWithArray() throws JsonLogicException {
37+
String json = "{\"+\":[2,[[3,4],5]]}";
38+
Object result = jsonLogic.apply(json, null);
39+
40+
assertEquals(5.0, result); // This matches reference impl at jsonlogic.com
41+
}
42+
3543
@Test
3644
public void testStringAdd() throws JsonLogicException {
3745
assertNull(jsonLogic.apply("{\"+\" : \"foo\"}", null));
@@ -79,6 +87,14 @@ public void testMultiMultiply() throws JsonLogicException {
7987
assertEquals(32.0, result);
8088
}
8189

90+
@Test
91+
public void testMultiplyWithArray() throws JsonLogicException {
92+
String json = "{\"*\":[2,[[3, 4], 5]]}";
93+
Object result = jsonLogic.apply(json, null);
94+
95+
assertEquals(6.0, result); // This matches reference impl at jsonlogic.com
96+
}
97+
8298
@Test
8399
public void testDivide() throws JsonLogicException {
84100
String json = "{\"/\":[4,2]}";

0 commit comments

Comments
 (0)