rules.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { Class } = require('../core/heritage');
  9. const { MatchPattern } = require('./match-pattern');
  10. const { on, off, emit } = require('../event/core');
  11. const { method } = require('../lang/functional');
  12. const objectUtil = require('./object');
  13. const { EventTarget } = require('../event/target');
  14. const { List, addListItem, removeListItem } = require('./list');
  15. // Should deprecate usage of EventEmitter/compose
  16. const Rules = Class({
  17. implements: [
  18. EventTarget,
  19. List
  20. ],
  21. add: function(...rules) [].concat(rules).forEach(function onAdd(rule) {
  22. addListItem(this, rule);
  23. emit(this, 'add', rule);
  24. }, this),
  25. remove: function(...rules) [].concat(rules).forEach(function onRemove(rule) {
  26. removeListItem(this, rule);
  27. emit(this, 'remove', rule);
  28. }, this),
  29. get: function(rule) {
  30. let found = false;
  31. for (let i in this) if (this[i] === rule) found = true;
  32. return found;
  33. },
  34. // Returns true if uri matches atleast one stored rule
  35. matchesAny: function(uri) !!filterMatches(this, uri).length,
  36. toString: function() '[object Rules]'
  37. });
  38. exports.Rules = Rules;
  39. function filterMatches(instance, uri) {
  40. let matches = [];
  41. for (let i in instance) {
  42. if (new MatchPattern(instance[i]).test(uri)) matches.push(instance[i]);
  43. }
  44. return matches;
  45. }