-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoutePath.js
70 lines (57 loc) · 1.6 KB
/
RoutePath.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
class RoutePath {
static forwardSlash = /\//;
static startsWithColon = /^\:/;
static validChars = '([a-zA-Z0-9-_~\\.%@]+)';
static matchForwardSlash = "\\/";
constructor(pattern, action, options) {
this.rawPattern = pattern;
this.action = action;
this.options = options || {};
this.fragments = [];
this.tokens = [];
this.setPattern(pattern);
}
setPattern(pattern){
if (pattern instanceof RegExp) {
this.pattern = pattern;
} else {
this.pattern = this.compile(pattern);
}
}
compile(pattern) {
let parts = pattern.split(RoutePath.forwardSlash);
parts.forEach((part, index) => {
if (part.match(RoutePath.startsWithColon)) {
this.tokens.push(part.replace(RoutePath.startsWithColon, ''));
this.fragments.push(RoutePath.validChars);
} else {
this.fragments.push(part);
}
});
return this.compileRegexp();
}
compileRegexp() {
return new RegExp(this.fragments.join(RoutePath.matchForwardSlash) + "$");
}
parseTokens(path) {
// unsure why +1
let tokenLength = this.tokens.length + 1;
let matches = path.match(this.pattern);
if (!matches) {
return [];
}
let values = matches.slice(1, tokenLength);
return this.tokens.reduce((finalValues, token, index, tokens) => {
finalValues[token] = values[index];
return finalValues;
},
{} // initial finalValues
);
}
}
if (typeof module != 'undefined') {
module.exports = {
RoutePath: RoutePath
};
}
export default RoutePath;