Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "reduce" model #5

Merged
merged 1 commit into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pydantic_jsonlogic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,14 @@ class Map(BaseJSONLogicOperation):
# The operation to be performed on each element of the array
BaseJSONLogicOperation,
]


class Reduce(BaseJSONLogicOperation):
reduce: tuple[
# An array or an operation that produces an array
list[Any] | Var | Missing | MissingSome | If | Merge | Filter | Map,
# The operation to be performed for each element of the array
BaseJSONLogicOperation,
# The initial accumulator value
Any,
]
25 changes: 25 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
NotEquals,
NotNot,
Or,
Reduce,
StrictEquals,
StrictNotEquals,
Substr,
Expand Down Expand Up @@ -506,3 +507,27 @@ def test_filter(json: str) -> None:
)
def test_map(json: str) -> None:
Map.model_validate_json(json)


@pytest.mark.parametrize(
"json",
[
"""{"reduce":[
{"var":"integers"},
{"+":[{"var":"current"}, {"var":"accumulator"}]},
0
]}""",
"""{"reduce":[
{"var":"integers"},
{"+":[{"var":"current"}, {"var":"accumulator"}]},
{"var": "start_with"}
]}""",
"""{"reduce":[
{"var":"integers"},
{"*":[{"var":"current"}, {"var":"accumulator"}]},
1
]}""",
],
)
def test_reduce(json: str) -> None:
Reduce.model_validate_json(json)