Get rid of regexp and handle cursor in trim in doc printer (#13426)

This commit is contained in:
Georgii Dolzhykov authored and GitHub committed 2022-09-06 15:57:47 +03:00
1 parent a6d6c9c3a2
commit 5766433a62
2 files changed
+52 -15

No files matched your search

+29 -13
View File
@@ -142,27 +142,43 @@ function generateInd(ind, newPart, options) {
}
}
// TODO: Skip cursor placeholder
// Trim `Tab(U+0009)` and `Space(U+0020)` at the end of line
function trim(out) {
let trimCount = 0;
let cursorCount = 0;
let outIndex = out.length;
while (out.length > 0) {
const last = getLast(out);
if (typeof last !== "string") {
break;
outer: while (outIndex--) {
const last = out[outIndex];
if (last === CURSOR_PLACEHOLDER) {
cursorCount++;
continue;
}
const trimmed = last.replace(/[\t ]*$/, "");
trimCount += last.length - trimmed.length;
if (trimmed !== "") {
out[out.length - 1] = trimmed;
break;
if (process.env.NODE_ENV !== "production" && typeof last !== "string") {
throw new Error(`Unexpected value in trim: '${typeof last}'`);
}
// All `Tab` or `Space`
out.length -= 1;
// Not using a regexp here because regexps for trimming off trailing
// characters are known to have performance issues.
for (let charIndex = last.length - 1; charIndex >= 0; charIndex--) {
const char = last[charIndex];
if (char === " " || char === "\t") {
trimCount++;
} else {
out[outIndex] = last.slice(0, charIndex + 1);
break outer;
}
}
}
if (trimCount > 0 || cursorCount > 0) {
out.length = outIndex + 1;
while (cursorCount-- > 0) {
out.push(CURSOR_PLACEHOLDER);
}
}
return trimCount;