-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouteMatcher.js
60 lines (52 loc) · 1.5 KB
/
routeMatcher.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
define(function(){
function normalize(path, keys, sensitive, strict) {
if (path instanceof RegExp) return path;
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional){
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}
function RouteMatcher(path,options){
options = options || {};
this.path = path;
this.regexp = normalize(path
, this.keys = []
, options.sensitive
, options.strict);
};
RouteMatcher.prototype.match = function(path) {
var keys = this.keys
, params = [];
if (captures = this.regexp.exec(path)) {
for (var j = 1, jlen = captures.length; j < jlen; ++j) {
var key = keys[j-1]
, val = 'string' == typeof captures[j]
? decodeURIComponent(captures[j])
: captures[j];
if (key) {
params[key.name] = val;
} else {
params.push(val);
}
}
}
return params;
}
function matchCur(path,options) {
return (new RouteMatcher(path,options)).match(window.location.pathname);
}
matchCur.Matcher = RouteMatcher;
return matchCur
});