UNPKG

794 BJavaScriptView Raw
1class Rule {
2 constructor({ test, value }) {
3 if (!(test instanceof RegExp)) {
4 throw new TypeError('`test` should be a regexp');
5 }
6
7 this.test = test;
8 this.value = value;
9 }
10
11 /**
12 * @param {string} value
13 * @return {boolean}
14 */
15 match(value) {
16 return this.test.test(value);
17 }
18}
19
20class RuleSet {
21 /**
22 * @param {Array<{test: RegExp, uri: string}>} rules
23 */
24 constructor(rules) {
25 if (!Array.isArray(rules)) {
26 throw new TypeError('`data` should be an array');
27 }
28
29 this.rules = rules.map(params => new Rule(params));
30 }
31
32 /**
33 * @param {string} value
34 * @return {Rule|null}
35 */
36 getMatchedRule(value) {
37 return this.rules.find(rule => rule.match(value)) || null;
38 }
39}
40
41module.exports = RuleSet;
42module.exports.Rule = Rule;