pattern.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const escapeRegExp = require('./escape_regexp');
  3. const rParam = /([:*])([\w?]*)?/g;
  4. class Pattern {
  5. constructor(rule) {
  6. if (rule instanceof Pattern) {
  7. return rule;
  8. } else if (typeof rule === 'function') {
  9. this.match = rule;
  10. } else if (rule instanceof RegExp) {
  11. this.match = regexFilter(rule);
  12. } else if (typeof rule === 'string') {
  13. this.match = stringFilter(rule);
  14. } else {
  15. throw new TypeError('rule must be a function, a string or a regular expression.');
  16. }
  17. }
  18. test(str) {
  19. return Boolean(this.match(str));
  20. }
  21. }
  22. function regexFilter(rule) {
  23. return str => str.match(rule);
  24. }
  25. function stringFilter(rule) {
  26. const params = [];
  27. const regex = escapeRegExp(rule)
  28. .replace(/\\([*?])/g, '$1')
  29. .replace(rParam, (match, operator, name) => {
  30. let str = '';
  31. if (operator === '*') {
  32. str = '(.*)?';
  33. } else {
  34. str = '([^\\/]+)';
  35. }
  36. if (name) {
  37. if (name[name.length - 1] === '?') {
  38. name = name.slice(0, name.length - 1);
  39. str += '?';
  40. }
  41. params.push(name);
  42. }
  43. return str;
  44. });
  45. return str => {
  46. const match = str.match(regex);
  47. if (!match) return;
  48. const result = {};
  49. for (let i = 0, len = match.length; i < len; i++) {
  50. const name = params[i - 1];
  51. result[i] = match[i];
  52. if (name) result[name] = match[i];
  53. }
  54. return result;
  55. };
  56. }
  57. module.exports = Pattern;