forked from mafintosh/router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatcher.js
More file actions
51 lines (39 loc) · 1.17 KB
/
matcher.js
File metadata and controls
51 lines (39 loc) · 1.17 KB
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
var decode = function(str) {
try {
return decodeURIComponent(str);
} catch(err) {
return str;
}
};
module.exports = function(pattern) {
if (typeof pattern !== 'string') { // regex
return function(url) {
return url.match(pattern);
};
}
var keys = [];
pattern = pattern.replace(/:(\w+)/g, '{$1}').replace('{*}', '*'); // normalize
pattern = pattern.replace(/(\/)?(\.)?\{([^}]+)\}(?:\(([^)]*)\))?(\?)?/g, function(match, slash, dot, key, capture, opt, offset) {
var incl = (pattern[match.length+offset] || '/') === '/';
keys.push(key);
return (incl ? '(?:' : '')+(slash || '')+(incl ? '' : '(?:')+(dot || '')+'('+(capture || '[^/]+')+'))'+(opt || '');
});
pattern = pattern.replace(/([\/.])/g, '\\$1').replace(/\*/g, '(.+)');
pattern = new RegExp('^'+pattern+'[\\/]?$', 'i');
return function(str) {
var match = str.match(pattern);
if (!match) {
return match;
}
var map = {};
match.slice(1).forEach(function(param, i) {
var k = keys[i] = keys[i] || 'wildcard';
param = param && decode(param);
map[k] = map[k] ? [].concat(map[k]).concat(param) : param;
});
if (map.wildcard) {
map['*'] = map.wildcard;
}
return map;
};
};