-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs-xre.js
81 lines (74 loc) · 2.5 KB
/
js-xre.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
// https://github.com/jawj/js-xre
// Copyright (C) George MacKerron 2010 - 2017
// MIT licenced
const xRE = (function () {
function xRE(literals, ...values) { // tag function that returns a tag function
return (flagLiterals, ...flagValues) => {
const flags = reassembleTemplate(flagLiterals, flagValues);
const x = flags.indexOf('x') > -1;
const mm = flags.indexOf('mm') > -1;
const escapeValues = flags.indexOf('b') > -1;
const valueTransform = escapeValues ? xRE.escape : undefined;
const extendedSource = reassembleTemplate(
literals, values, true, undefined, valueTransform);
const nativeSource = transpile(extendedSource, x, mm);
const nativeFlags = flags.replace(/x|b/g, '').replace('mm', 'm');
return new RegExp(nativeSource, nativeFlags);
}
}
xRE.escape = (source) =>
String(source).replace(/[-\/\\^$.*+?()[\]{}|]/g, '\\$&');
reassembleTemplate = (literals, values, raw = false,
literalTransform = String, valueTransform = String) => {
if (typeof literals === 'string') return literals;
if (raw) literals = literals.raw;
let s = literalTransform(literals[0]);
for (let i = 1, len = literals.length; i < len; i++) s +=
valueTransform(values[i - 1]) + literalTransform(literals[i]);
return s;
}
transpile = (source, x, m) => {
if (!x && !m) return source;
const len = source.length;
let convertedSource = '', inCharClass = false, inComment = false, justBackslashed = false;
for (let i = 0; i < len; i++) {
let c = source.charAt(i);
if (justBackslashed) {
if (!inComment) convertedSource += c;
justBackslashed = false;
continue;
}
if (c == '\\') {
if (!inComment) convertedSource += c;
justBackslashed = true;
continue;
}
if (inCharClass) {
convertedSource += c;
if (c == ']') inCharClass = false;
continue;
}
if (inComment) {
if (c == "\n" || c == "\r") inComment = false;
continue;
}
if (c == '[') {
convertedSource += c;
inCharClass = true;
continue;
}
if (x && c == '#') {
inComment = true;
continue;
}
if (m && c == '.') {
convertedSource += '[\\s\\S]';
continue;
}
if (!x || !c.match(/\s/)) convertedSource += c;
}
return convertedSource;
}
return xRE;
})();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') module.exports = xRE;