Skip to content

Commit a99a6d8

Browse files
committed
JEP-16 Evaluates arithmetic expressions
1 parent 4863043 commit a99a6d8

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

jmespath/visitor.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,18 @@ class TreeInterpreter(Visitor):
107107
'gte': operator.ge
108108
}
109109
_EQUALITY_OPS = ['eq', 'ne']
110+
_ARITHMETIC_UNARY_FUNC = {
111+
'minus': operator.neg,
112+
'plus': lambda x: x
113+
}
114+
_ARITHMETIC_FUNC = {
115+
'div': operator.floordiv,
116+
'divide': operator.truediv,
117+
'minus': operator.sub,
118+
'modulo': operator.mod,
119+
'multiply': operator.mul,
120+
'plus': operator.add,
121+
}
110122
MAP_TYPE = dict
111123

112124
def __init__(self, options=None):
@@ -157,6 +169,19 @@ def visit_comparator(self, node, value):
157169
return None
158170
return comparator_func(left, right)
159171

172+
def visit_arithmetic_unary(self, node, value):
173+
operation = self._ARITHMETIC_UNARY_FUNC[node['value']]
174+
return operation(
175+
self.visit(node['children'][0], value)
176+
)
177+
178+
def visit_arithmetic(self, node, value):
179+
operation = self._ARITHMETIC_FUNC[node['value']]
180+
return operation(
181+
self.visit(node['children'][0], value),
182+
self.visit(node['children'][1], value)
183+
)
184+
160185
def visit_current(self, node, value):
161186
return value
162187

tests/compliance/arithmetic.json

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
[
2+
{
3+
"given": {
4+
"a": {
5+
"b": 1
6+
},
7+
"c": {
8+
"d": 2
9+
}
10+
},
11+
"cases": [
12+
{
13+
"expression": "`1` + `2`",
14+
"result": 3.0
15+
},
16+
{
17+
"expression": "`1` - `2`",
18+
"result": -1.0
19+
},
20+
{
21+
"expression": "`2` * `4`",
22+
"result": 8.0
23+
},
24+
{
25+
"expression": "`2` × `4`",
26+
"result": 8.0
27+
},
28+
{
29+
"expression": "`2` / `3`",
30+
"result": 0.6666666666666666
31+
},
32+
{
33+
"expression": "`2` ÷ `3`",
34+
"result": 0.6666666666666666
35+
},
36+
{
37+
"expression": "`10` % `3`",
38+
"result": 1.0
39+
},
40+
{
41+
"expression": "`10` // `3`",
42+
"result": 3.0
43+
},
44+
{
45+
"expression": "-`1` - + `2`",
46+
"result": -3.0
47+
},
48+
{
49+
"expression": "{ ab: a.b, cd: c.d } | ab + cd",
50+
"result": 3.0
51+
},
52+
{
53+
"expression": "{ ab: a.b, cd: c.d } | ab + cd × cd",
54+
"result": 5.0
55+
},
56+
{
57+
"expression": "{ ab: a.b, cd: c.d } | (ab + cd) × cd",
58+
"result": 6.0
59+
}
60+
]
61+
}
62+
]

0 commit comments

Comments
 (0)