-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (81 loc) · 1.78 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* @component route
* @description Route component
* @copyright 2013 Enrico Marino and Federico Spini
* @license MIT
*/
module.exports = Route;
/**
* @constructor Router
* @description Create a router.
* @api public
*/
function Route (path) {
if (!(this instanceof Route)) {
return new Route(path);
}
var result = this.create_regexp(path);
this.path = path;
this.keys = result.keys;
this.regexp = result.regexp;
}
/**
* @method match
* @description test if `path` matches this route
* @param {String} path path to test
* @return {Boolean} true if `path` matches this route
* false otherwise
* @api public
*/
Route.prototype.match = function (path) {
var params = [];
var keys = this.keys;
var regexp = this.regexp;
var match;
var n;
var i;
var key;
var val;
path = path.split('?')[0];
match = regexp.exec(path);
if (!match) {
return false;
}
match = match.splice(1);
n = match.length;
for (i = 0; i < n; i += 1) {
key = keys[i];
val = decodeURIComponent(match[i]);
if (key) {
params[key] = val;
} else {
params.push(val);
}
}
return params;
};
/**
* @method create_regexp
* @description Create the regexp
* @param {String} path
* @api private
*/
Route.prototype.create_regexp = function (path, keys) {
keys = keys || [];
path = path
.replace(/[\-{}\[\]+?.,\\\^$|#\s]/g, '\\$&')
.replace(/\((.*?)\)/g, function (match, key) {
keys.push(key);
return '([^\/]+)?';
})
.replace(/:(\w+)/g, function (match, key) {
keys.push(key);
return '([^\/]+)';
})
.replace(/\*(\w*)/g, function (match, key) {
keys.push(key);
return '(.*?)';
});
var regexp = new RegExp('^' + path + '$');
return { regexp: regexp, keys: keys };
};