displace-comments
Version:
Replace the comment with an equal amount of space from the code string
119 lines (114 loc) • 3.03 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/index.ts
var matchs = [
{
start: "/*",
end: /\*[\s]*?\//g,
type: "multiple"
},
{
start: "<!--",
end: "-->",
type: "html"
},
{
start: "//",
end: "\n",
type: "single"
}
];
var FILL = " ";
function discern(code) {
for (let i = 0; i < matchs.length && code.trim(); i++) {
const current = matchs[i];
if (!code.includes(current.start))
continue;
if (current.start === code) {
return current;
}
return discern(code.substring(0, code.length - 1));
}
}
function findMaxLen() {
let len = 0;
matchs.forEach((v) => {
const s = v.start;
if (s.length > len) {
len = s.length;
}
});
return len;
}
function core(code, m) {
Array.isArray(m) && matchs.push(__spreadProps(__spreadValues({}, m), {
type: "custom"
}));
const detail = [];
const length = findMaxLen();
for (let i = 0; i < code.length; i++) {
const subCode = code.substr(i, length);
if (!subCode.trim()) {
i += length - 1;
continue;
}
const cur = discern(subCode);
if (cur) {
const o = {
start: i,
type: cur.type
};
if (cur.end instanceof RegExp) {
cur.end.lastIndex = i;
const m2 = cur.end.exec(code);
if (m2) {
const end = m2.index + m2[0].length;
detail.push(__spreadProps(__spreadValues({}, o), {
end,
text: code.substring(i, end)
}));
i = end - 1;
}
continue;
}
const j = code.indexOf(cur.end, i + cur.end.length);
if (j > -1) {
const end = cur.end.length + j;
detail.push(__spreadProps(__spreadValues({}, o), {
end,
text: code.substring(i, end)
}));
i = end - 1;
}
}
}
return detail;
}
function displace(code, m) {
const detail = core(code, m);
detail.forEach((v) => {
code = code.replace(v.text, FILL.repeat(v.text.length) + "\n");
});
return code;
}
function parse(code, m) {
return core(code, m);
}
exports.displace = displace; exports.parse = parse;