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
Open
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
20 changes: 17 additions & 3 deletions v0/src/jsonLogic.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,26 +404,40 @@ function validateInlineRules(jsonSchema, sampleEmptyObject) {
* @param {Function} errorMessage - Function to generate custom error message.
* Receives the invalid rule part and should throw an error message string.
*/

function checkRuleIntegrity(
rule,
id,
data,
errorMessage = (item) =>
`[json-schema-form] json-logic error: rule "${id}" has no variable "${item.var}".`
`[json-schema-form] json-logic error: rule "${id}" has no variable "${item.var}".`,
inReduceOrMap = false
) {
Object.entries(rule ?? {}).map(([operator, subRule]) => {
if (!Array.isArray(subRule) && subRule !== null && subRule !== undefined) return;
throwIfUnknownOperator(operator, subRule, id);

// If we are within a reduce or map, we allow references to `accumulator` and/or `current`.
// We augment the data so that we still validate any other field.
const isReduceOrMap = inReduceOrMap || operator === 'reduce' || operator === 'map';

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

current: null,
}
: data;

subRule.map((item) => {
const isVar = item !== null && typeof item === 'object' && Object.hasOwn(item, 'var');
if (isVar) {
const exists = jsonLogic.apply({ var: removeIndicesFromPath(item.var) }, data);
const exists = jsonLogic.apply({ var: removeIndicesFromPath(item.var) }, validationData);
if (exists === null) {
throw Error(errorMessage(item));
}
} else {
checkRuleIntegrity(item, id, data);
checkRuleIntegrity(item, id, data, errorMessage, isReduceOrMap);
}
});
});
Expand Down
4 changes: 2 additions & 2 deletions v0/src/tests/jsonLogic.fixtures.js
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,7 @@ export const schemaWithReduceAccumulator = {
type: 'number',
'x-jsf-logic-computedAttrs': {
const: 'computed_work_hours_per_week',
defaultValue: 'computed_work_hours_per_week',
default: 'computed_work_hours_per_week',
title: '{{computed_work_hours_per_week}} hours per week',
},
},
Expand All @@ -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.

},
],
},
Expand Down