|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 "use strict"; |
|
6 |
|
7 module.metadata = { |
|
8 "stability": "unstable" |
|
9 }; |
|
10 |
|
11 const { Class } = require('../core/heritage'); |
|
12 const { MatchPattern } = require('./match-pattern'); |
|
13 const { on, off, emit } = require('../event/core'); |
|
14 const { method } = require('../lang/functional'); |
|
15 const objectUtil = require('./object'); |
|
16 const { EventTarget } = require('../event/target'); |
|
17 const { List, addListItem, removeListItem } = require('./list'); |
|
18 |
|
19 // Should deprecate usage of EventEmitter/compose |
|
20 const Rules = Class({ |
|
21 implements: [ |
|
22 EventTarget, |
|
23 List |
|
24 ], |
|
25 add: function(...rules) [].concat(rules).forEach(function onAdd(rule) { |
|
26 addListItem(this, rule); |
|
27 emit(this, 'add', rule); |
|
28 }, this), |
|
29 remove: function(...rules) [].concat(rules).forEach(function onRemove(rule) { |
|
30 removeListItem(this, rule); |
|
31 emit(this, 'remove', rule); |
|
32 }, this), |
|
33 get: function(rule) { |
|
34 let found = false; |
|
35 for (let i in this) if (this[i] === rule) found = true; |
|
36 return found; |
|
37 }, |
|
38 // Returns true if uri matches atleast one stored rule |
|
39 matchesAny: function(uri) !!filterMatches(this, uri).length, |
|
40 toString: function() '[object Rules]' |
|
41 }); |
|
42 exports.Rules = Rules; |
|
43 |
|
44 function filterMatches(instance, uri) { |
|
45 let matches = []; |
|
46 for (let i in instance) { |
|
47 if (new MatchPattern(instance[i]).test(uri)) matches.push(instance[i]); |
|
48 } |
|
49 return matches; |
|
50 } |