rules.js 794 B

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