/
permalink.js
58 lines (41 loc) · 1.19 KB
/
permalink.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
'use strict';
const escapeRegExp = require('./escape_regexp');
const rParam = /:(\w+)/g;
function Permalink(rule, options) {
if (!rule) throw new TypeError('rule is required!');
options = options || {};
const segments = options.segments || {};
const params = [];
const regex = escapeRegExp(rule)
.replace(rParam, (match, name) => {
params.push(name);
if (Object.prototype.hasOwnProperty.call(segments, name)) {
const segment = segments[name];
if (segment instanceof RegExp) {
return segment.source;
}
return segment;
}
return '(.+?)';
});
this.rule = rule;
this.regex = new RegExp(`^${regex}$`);
this.params = params;
}
Permalink.prototype.test = function(str) {
return this.regex.test(str);
};
Permalink.prototype.parse = function(str) {
const match = str.match(this.regex);
const { params } = this;
const result = {};
if (!match) return;
for (let i = 1, len = match.length; i < len; i++) {
result[params[i - 1]] = match[i];
}
return result;
};
Permalink.prototype.stringify = function(data) {
return this.rule.replace(rParam, (match, name) => data[name]);
};
module.exports = Permalink;