UNPKG

1.78 kBJavaScriptView Raw
1var lodash = require('lodash');
2
3function RuleList() {
4 this.rulesMap = {};
5 this.subsMap = {};
6}
7module.exports = RuleList;
8
9RuleList.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
19RuleList.prototype.getRule = function (ruleName) {
20 return this.rulesMap[ruleName];
21};
22
23RuleList.prototype.getSubscribers = function (subName) {
24 var subs = this.subsMap[subName];
25
26 return subs ? subs : [];
27};
28
29RuleList.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
40RuleList.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
50RuleList.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
61RuleList.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
74RuleList.prototype.forEach = function (func) {
75 lodash.forOwn(this.rulesMap, function (rule) {
76 // this function call is wrapped because lodash.forOwn
77 // passes back 3 args, this method should only pass back 1
78 func(rule);
79 });
80};