forked from hexojs/hexo-util
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattern.js
73 lines (57 loc) · 1.45 KB
/
pattern.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use strict';
const escapeRegExp = require('./escape_regexp');
const rParam = /([:*])([\w?]*)?/g;
class Pattern {
constructor(rule) {
if (rule instanceof Pattern) {
return rule;
} else if (typeof rule === 'function') {
this.match = rule;
} else if (rule instanceof RegExp) {
this.match = regexFilter(rule);
} else if (typeof rule === 'string') {
this.match = stringFilter(rule);
} else {
throw new TypeError('rule must be a function, a string or a regular expression.');
}
}
test(str) {
return Boolean(this.match(str));
}
}
function regexFilter(rule) {
return str => str.match(rule);
}
function stringFilter(rule) {
const params = [];
const regex = escapeRegExp(rule)
.replace(/\\([*?])/g, '$1')
.replace(rParam, (match, operator, name) => {
let str = '';
if (operator === '*') {
str = '(.*)?';
} else {
str = '([^\\/]+)';
}
if (name) {
if (name[name.length - 1] === '?') {
name = name.slice(0, name.length - 1);
str += '?';
}
params.push(name);
}
return str;
});
return str => {
const match = str.match(regex);
if (!match) return;
const result = {};
for (let i = 0, len = match.length; i < len; i++) {
const name = params[i - 1];
result[i] = match[i];
if (name) result[name] = match[i];
}
return result;
};
}
module.exports = Pattern;