Skip to content

feat: allow accumulator/current in reduce/map operations #225

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

cammellos
Copy link

As part of removing some code from the dragon frontend, to be able to use it in our SDK/API, I had to move some frontend logic to the backend.
To do that, I need to use reduce, in order to calculate the length on a array. This is in theory supported by json-logic-js.
The issue is that we run validation against the data provided, but we don't accommodate for the fact that if we are within a reduce/map block, we should allow current and accumulator.
This code enriches the validation data if we are within a reduce/map block, while it maintains checking the integrity of the rest of the variables.

Let me know if the implementation is what you expect or you'd rather be different, thank you!

@@ -1073,7 +1073,7 @@ export const schemaWithReduceAccumulator = {
'*': [
{ var: 'working_hours_per_day' },
{
reduce: [{ var: 'work_days' }, { '+': [{ var: ['accumulator', 0] }, 1] }, 0],
reduce: [{ var: 'work_days' }, { '+': [{ var: "accumulator" }, 1] }, 0],
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor: for consistency we should keep the single quotes.

const validationData = isReduceOrMap
? {
...data,
accumulator: 0,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting the initial value of the accumulator to 0, we're assuming that the final result of the reduce will always be a number. Is this intentional? I'm thinking about a different scenario where you might want to concatenate strings:

{"reduce":[
    {"var":"integers"},
    {"+":[{"var":"current"}, {"var":"accumulator"}]},
    ""
]}

When running jsonLogic.apply, this would result in 0Hello World, right?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mmh, yes, that could be a problem, the logic would work since this is only for checking the integrity of the rules, and when actually running it for your form it will use the right parameters, but it would be a problem if you say have a division instead, let me create a test to see, good point

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants