forked from sindresorhus/subsume
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (32 loc) · 1.03 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
//'use strict';
const crypto = require('crypto');
const escapeStringRegexp = require('escape-string-regexp');
function subsume(id) {
function uniqueString() {
return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
}
if (id && (id.includes('Qq-') || id.includes('Zz-'))) {
throw new Error("'Qq-' and 'Zz-' cannot be used in the ID");
}
this.id = id ? id : uniqueString();
this.prefix = 'Qq-' + this.id + '-qQ';
this.postfix = 'Zz-' + this.id + '-zZ';
this.regex = new RegExp(escapeStringRegexp(this.prefix) + '([\\S\\s]*)' + escapeStringRegexp(this.postfix), 'g');
}
subsume.prototype.parse = function parse(str, id) {
function parse(str) {
const ret = {};
ret.rest = str.replace(this.regex, function (m, p1) {
if (p1) {
ret.data = p1;
}
return '';
});
return ret;
}
return (new Subsume(id)).parse(str);
};
subsume.prototype.compose = function compose(str) {
return this.prefix + str + this.postfix;
}
exports = module.exports = subsume;