1 | var lodash = require('lodash');
|
2 |
|
3 | function RuleList() {
|
4 | this.rulesMap = {};
|
5 | this.subsMap = {};
|
6 | }
|
7 | module.exports = RuleList;
|
8 |
|
9 | RuleList.fromRuleMap = function (ruleMap) {
|
10 | var ruleList = new RuleList();
|
11 |
|
12 | lodash.forOwn(ruleMap, function (rule) {
|
13 | ruleList.addRule(rule);
|
14 | });
|
15 |
|
16 | return ruleList;
|
17 | };
|
18 |
|
19 | RuleList.prototype.getRule = function (ruleName) {
|
20 | return this.rulesMap[ruleName];
|
21 | };
|
22 |
|
23 | RuleList.prototype.getSubscribers = function (subName) {
|
24 | var subs = this.subsMap[subName];
|
25 |
|
26 | return subs ? subs : [];
|
27 | };
|
28 |
|
29 | RuleList.prototype.addRule = function (rule) {
|
30 | var ruleName = rule.name;
|
31 |
|
32 | if (this.rulesMap[ruleName]) {
|
33 | this.removeRule(ruleName);
|
34 | }
|
35 |
|
36 | this.subscribeRule(rule);
|
37 | this.rulesMap[ruleName] = rule;
|
38 | };
|
39 |
|
40 | RuleList.prototype.removeRule = function (ruleName) {
|
41 | var rule = this.getRule(ruleName);
|
42 |
|
43 | if (rule) {
|
44 | this.unsubscribeRule(rule);
|
45 | }
|
46 |
|
47 | delete this.rulesMap[ruleName];
|
48 | };
|
49 |
|
50 | RuleList.prototype.unsubscribeRule = function (rule) {
|
51 | if (!rule.on) {
|
52 | return;
|
53 | }
|
54 |
|
55 | rule.on.forEach(function (subName) {
|
56 | var subIndex = this.subsMap[subName].indexOf(rule);
|
57 | this.subsMap[subName].splice(subIndex, 1);
|
58 | }.bind(this));
|
59 | };
|
60 |
|
61 | RuleList.prototype.subscribeRule = function (rule) {
|
62 | if (!rule.on) {
|
63 | return;
|
64 | }
|
65 |
|
66 | rule.on.forEach(function (subName) {
|
67 | if (!this.subsMap[subName]) {
|
68 | this.subsMap[subName] = [];
|
69 | }
|
70 | this.subsMap[subName].push(rule);
|
71 | }.bind(this));
|
72 | };
|
73 |
|
74 | RuleList.prototype.forEach = function (func) {
|
75 | lodash.forOwn(this.rulesMap, function (rule) {
|
76 |
|
77 |
|
78 | func(rule);
|
79 | });
|
80 | };
|