63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import * as plugins from './smartrule.plugins';
|
|
import { Rule, TCheckFunc, TActionFunc, TTreeActionResult } from './smartrule.classes.rule';
|
|
|
|
export class SmartRule<T> {
|
|
public rules: Array<Rule<T>> = [];
|
|
|
|
/**
|
|
* makes a decision based on the given obect and the given rules
|
|
* @param objectArg
|
|
*/
|
|
public async makeDecision(objectArg: T) {
|
|
// 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: number) => {
|
|
return this.rules.filter(rule => {
|
|
return rule.priority === priorityStart;
|
|
});
|
|
};
|
|
|
|
// lets run the checks
|
|
const runNextBatch = async (startPriority: number) => {
|
|
const nextBatch = getNextParallelBatch(0);
|
|
const outcomes: TTreeActionResult[] = [];
|
|
for (const rule of nextBatch) {
|
|
const checkResult = await rule.checkFunction(objectArg);
|
|
if (checkResult.startsWith("apply")) {
|
|
await rule.actionFunction(objectArg);
|
|
}
|
|
outcomes.push(checkResult);
|
|
};
|
|
|
|
const finalOutcome: TTreeActionResult = outcomes.reduce((previous, current, index, array) => {
|
|
if (current.includes('continue') || previous.includes('continue')) {
|
|
return 'continue';
|
|
} else {
|
|
return 'stop';
|
|
}
|
|
});
|
|
if (finalOutcome === 'stop') {
|
|
return;
|
|
}
|
|
|
|
if (startPriority < this.rules[this.rules.length-1].priority) {
|
|
runNextBatch(startPriority++);
|
|
}
|
|
};
|
|
|
|
await runNextBatch(0);
|
|
}
|
|
|
|
public createRule(priorityArg: number, checkFunctionArg: TCheckFunc<T>, actionFunctionArg: TActionFunc) {
|
|
const rule = new Rule<T>(this, priorityArg, checkFunctionArg, actionFunctionArg);
|
|
this.rules.push(rule);
|
|
}
|
|
} |