@luvies/business-rules
Version:
A JS-expression-based rules engine
46 lines • 1.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class DependencyGraph {
constructor(nodes) {
// Source -> {Targets}
this._dependencies = new Map();
this._nodes = nodes;
}
canCall(source, target) {
// Now we need to check the reverse. So if the target has already called the source.
// First check direct, then go to recursive hell.
const targetCalls = this._dependencies.get(target);
if (!targetCalls) {
return true;
}
if (targetCalls.has(source)) {
return false;
}
for (const targetCall of targetCalls) {
if (!this.canCall(source, targetCall)) {
return false;
}
}
return true;
}
addDependency(source, target) {
if (!this._nodes.includes(source)) {
throw new Error('Source not found in list');
}
if (!this._nodes.includes(target)) {
throw new Error('Target not found in list');
}
if (!this.canCall(source, target)) {
throw new Error('Circular dependency detected');
}
const calls = this._dependencies.get(source);
if (calls) {
calls.add(target);
}
else {
this._dependencies.set(source, new Set([target]));
}
}
}
exports.DependencyGraph = DependencyGraph;
//# sourceMappingURL=dependency-graph.js.map