Skip to content

Commit

Permalink
feat(jexl): add length transform
Browse files Browse the repository at this point in the history
  • Loading branch information
anehx committed Aug 30, 2024
1 parent 313f9f2 commit b4fbd99
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
7 changes: 7 additions & 0 deletions caluma/caluma_core/jexl.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ def __init__(self, *args, **kwargs):
self.add_transform("mapby", self._mapby_transform)
self.add_transform("stringify", lambda obj: json.dumps(obj))
self.add_transform("flatten", self._flatten_transform)
self.add_transform("length", self._length_transform)
self.add_binary_operator(
"intersects", 20, lambda left, right: any(x in right for x in left)
)
Expand Down Expand Up @@ -159,6 +160,12 @@ def _flatten_transform(self, arr, *options):

return list(chain(*arr))

def _length_transform(self, value, *options):
try:
return len(value)
except TypeError:
return None

def evaluate(self, expression, context=None):
self._expr_stack.append(expression)
try:
Expand Down
7 changes: 7 additions & 0 deletions caluma/caluma_core/tests/test_jexl.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,13 @@ def test_intersects_operator(expression, result):
["some-value", "some-other-value"],
),
("null|flatten", None),
# count
("['test1', 'test2']|length", 2),
("{key: 1}|length", 1),
("'foobar'|length", 6),
("1|length", None),
("1.1|length", None),
("null|length", None),
],
)
def test_simple_transforms(expression, result):
Expand Down

0 comments on commit b4fbd99

Please sign in to comment.