1 | class 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 |
|
13 |
|
14 |
|
15 | match(value) {
|
16 | return this.test.test(value);
|
17 | }
|
18 | }
|
19 |
|
20 | class RuleSet {
|
21 | |
22 |
|
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 |
|
34 |
|
35 |
|
36 | getMatchedRule(value) {
|
37 | return this.rules.find(rule => rule.match(value)) || null;
|
38 | }
|
39 | }
|
40 |
|
41 | module.exports = RuleSet;
|
42 | module.exports.Rule = Rule;
|