Skip to content

Commit

Permalink
JEP-16 Evaluates arithmetic expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
springcomp committed Oct 22, 2022
1 parent 4863043 commit a99a6d8
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
25 changes: 25 additions & 0 deletions jmespath/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,18 @@ class TreeInterpreter(Visitor):
'gte': operator.ge
}
_EQUALITY_OPS = ['eq', 'ne']
_ARITHMETIC_UNARY_FUNC = {
'minus': operator.neg,
'plus': lambda x: x
}
_ARITHMETIC_FUNC = {
'div': operator.floordiv,
'divide': operator.truediv,
'minus': operator.sub,
'modulo': operator.mod,
'multiply': operator.mul,
'plus': operator.add,
}
MAP_TYPE = dict

def __init__(self, options=None):
Expand Down Expand Up @@ -157,6 +169,19 @@ def visit_comparator(self, node, value):
return None
return comparator_func(left, right)

def visit_arithmetic_unary(self, node, value):
operation = self._ARITHMETIC_UNARY_FUNC[node['value']]
return operation(
self.visit(node['children'][0], value)
)

def visit_arithmetic(self, node, value):
operation = self._ARITHMETIC_FUNC[node['value']]
return operation(
self.visit(node['children'][0], value),
self.visit(node['children'][1], value)
)

def visit_current(self, node, value):
return value

Expand Down
62 changes: 62 additions & 0 deletions tests/compliance/arithmetic.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
[
{
"given": {
"a": {
"b": 1
},
"c": {
"d": 2
}
},
"cases": [
{
"expression": "`1` + `2`",
"result": 3.0
},
{
"expression": "`1` - `2`",
"result": -1.0
},
{
"expression": "`2` * `4`",
"result": 8.0
},
{
"expression": "`2` × `4`",
"result": 8.0
},
{
"expression": "`2` / `3`",
"result": 0.6666666666666666
},
{
"expression": "`2` ÷ `3`",
"result": 0.6666666666666666
},
{
"expression": "`10` % `3`",
"result": 1.0
},
{
"expression": "`10` // `3`",
"result": 3.0
},
{
"expression": "-`1` - + `2`",
"result": -3.0
},
{
"expression": "{ ab: a.b, cd: c.d } | ab + cd",
"result": 3.0
},
{
"expression": "{ ab: a.b, cd: c.d } | ab + cd × cd",
"result": 5.0
},
{
"expression": "{ ab: a.b, cd: c.d } | (ab + cd) × cd",
"result": 6.0
}
]
}
]

0 comments on commit a99a6d8

Please sign in to comment.