smartrule/dist_ts/smartrule.classes.smartrule.js

69 lines
5.2 KiB
JavaScript
Raw Normal View History

2022-08-07 09:18:02 +00:00
import './smartrule.plugins.js';
import { Rule } from './smartrule.classes.rule.js';
export class SmartRule {
constructor() {
this.rules = [];
}
/**
* makes a decision based on the given obect and the given rules
* @param objectArg
*/
async makeDecision(objectArg) {
// lets sort the rules
this.rules = this.rules.sort((a, b) => {
if (a.priority > b.priority) {
return 1;
}
else {
return 0;
}
});
// gets the next batch with the same priority
const getNextParallelBatch = (priorityStart) => {
return this.rules.filter(rule => {
return rule.priority === priorityStart;
});
};
// lets run the checks
const runNextBatch = async (startPriority, runRulesAmount) => {
const nextBatch = getNextParallelBatch(startPriority);
runRulesAmount = runRulesAmount + nextBatch.length;
const outcomes = [];
for (const rule of nextBatch) {
const checkResult = await rule.checkFunction(objectArg);
checkResult
? null
: console.log('WARNING!!! Please make sure your rule always returns a statement of how to continue!');
if (checkResult.startsWith('apply')) {
await rule.actionFunction(objectArg); // here the action function is run
}
outcomes.push(checkResult);
}
if (outcomes.length > 0) {
const finalOutcomeOfBatch = outcomes.reduce((previous, current, index, array) => {
if (current.includes('continue') || previous.includes('continue')) {
return 'continue';
}
else {
return 'stop';
}
});
if (finalOutcomeOfBatch === 'stop') {
return;
}
}
if (runRulesAmount < this.rules.length) {
await runNextBatch(startPriority + 1, runRulesAmount);
}
else {
return;
}
};
await runNextBatch(0, 0);
}
createRule(priorityArg, checkFunctionArg, actionFunctionArg) {
const rule = new Rule(this, priorityArg, checkFunctionArg, actionFunctionArg);
this.rules.push(rule);
}
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRydWxlLmNsYXNzZXMuc21hcnRydWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRydWxlLmNsYXNzZXMuc21hcnRydWxlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQXlCLH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