addon-sdk/source/lib/sdk/util/rules.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/lib/sdk/util/rules.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,50 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +"use strict";
     1.9 +
    1.10 +module.metadata = {
    1.11 +  "stability": "unstable"
    1.12 +};
    1.13 +
    1.14 +const { Class } = require('../core/heritage');
    1.15 +const { MatchPattern } = require('./match-pattern');
    1.16 +const { on, off, emit } = require('../event/core');
    1.17 +const { method } = require('../lang/functional');
    1.18 +const objectUtil = require('./object');
    1.19 +const { EventTarget } = require('../event/target');
    1.20 +const { List, addListItem, removeListItem } = require('./list');
    1.21 +
    1.22 +// Should deprecate usage of EventEmitter/compose
    1.23 +const Rules = Class({
    1.24 +  implements: [
    1.25 +    EventTarget,
    1.26 +    List
    1.27 +  ],
    1.28 +  add: function(...rules) [].concat(rules).forEach(function onAdd(rule) {
    1.29 +    addListItem(this, rule);
    1.30 +    emit(this, 'add', rule);
    1.31 +  }, this),
    1.32 +  remove: function(...rules) [].concat(rules).forEach(function onRemove(rule) {
    1.33 +    removeListItem(this, rule);
    1.34 +    emit(this, 'remove', rule);
    1.35 +  }, this),
    1.36 +  get: function(rule) {
    1.37 +    let found = false;
    1.38 +    for (let i in this) if (this[i] === rule) found = true;
    1.39 +    return found;
    1.40 +  },
    1.41 +  // Returns true if uri matches atleast one stored rule
    1.42 +  matchesAny: function(uri) !!filterMatches(this, uri).length,
    1.43 +  toString: function() '[object Rules]'
    1.44 +});
    1.45 +exports.Rules = Rules;
    1.46 +
    1.47 +function filterMatches(instance, uri) {
    1.48 +  let matches = [];
    1.49 +  for (let i in instance) {
    1.50 +    if (new MatchPattern(instance[i]).test(uri)) matches.push(instance[i]);
    1.51 +  }
    1.52 +  return matches;
    1.53 +}

mercurial