Skip to content

Commit

Permalink
refactor(permalink): prototype to class syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
curbengh committed Apr 27, 2020
1 parent ec14aed commit 4de28ea
Showing 1 changed file with 37 additions and 44 deletions.
81 changes: 37 additions & 44 deletions lib/permalink.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,55 +4,48 @@ const escapeRegExp = require('./escape_regexp');

const rParam = /:(\w*[^_\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;
class Permalink {
constructor(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;
}

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;
test(str) {
return this.regex.test(str);
}

for (let i = 1, len = match.length; i < len; i++) {
result[params[i - 1]] = match[i];
parse(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;
}

return result;
};
stringify(data) {
return this.rule.replace(rParam, (match, name) => data[name]);
}
}

Permalink.prototype.stringify = function(data) {
return this.rule.replace(rParam, (match, name) => data[name]);
};

module.exports = Permalink;

0 comments on commit 4de28ea

Please sign in to comment.