Reuse getPreferredQuote (#14474)

This commit is contained in:
fisker Cheung authored and GitHub committed 2023-03-10 10:03:20 +08:00
1 parent 80419fa69e
commit 8f679c2fd8
3 files changed
+5 -30

No files matched your search

+3 -8
View File
@@ -5,12 +5,9 @@
import { fill, group, hardline } from "../document/builders.js";
import { cleanDoc, replaceEndOfLine } from "../document/utils.js";
import UnexpectedNodeError from "../utils/unexpected-node-error.js";
import getPreferredQuote from "../utils/get-preferred-quote.js";
import clean from "./clean.js";
import {
countChars,
unescapeQuoteEntities,
getTextValueParts,
} from "./utils/index.js";
import { unescapeQuoteEntities, getTextValueParts } from "./utils/index.js";
import preprocess from "./print-preprocess.js";
import { insertPragma } from "./pragma.js";
import { locStart, locEnd } from "./loc.js";
@@ -95,9 +92,7 @@ function genericPrint(path, options, print) {
return node.rawName;
}
const value = unescapeQuoteEntities(node.value);
const singleQuoteCount = countChars(value, "'");
const doubleQuoteCount = countChars(value, '"');
const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
const { quote } = getPreferredQuote(value, '"');
return [
node.rawName,
"=",
-11
View File
@@ -546,16 +546,6 @@ function dedentString(text, minIndent = getMinIndentation(text)) {
.join("\n");
}
function countChars(text, char) {
let counter = 0;
for (let i = 0; i < text.length; i++) {
if (text[i] === char) {
counter++;
}
}
return counter;
}
function unescapeQuoteEntities(text) {
return text.replaceAll("&apos;", "'").replaceAll("&quot;", '"');
}
@@ -629,7 +619,6 @@ export {
htmlTrimPreserveIndentation,
getLeadingAndTrailingHtmlWhitespace,
canHaveInterpolation,
countChars,
dedentString,
forceBreakChildren,
forceBreakContent,
+2 -11
View File
@@ -2,6 +2,7 @@ import collapseWhiteSpace from "collapse-white-space";
import getMinNotPresentContinuousCount from "../utils/get-min-not-present-continuous-count.js";
import getMaxContinuousCount from "../utils/get-max-continuous-count.js";
import getStringWidth from "../utils/get-string-width.js";
import getPreferredQuote from "../utils/get-preferred-quote.js";
import {
breakParent,
join,
@@ -808,17 +809,7 @@ function printTitle(title, options, printSpace = true) {
if (title.includes('"') && title.includes("'") && !title.includes(")")) {
return `(${title})`; // avoid escaped quotes
}
// faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
const singleCount = title.split("'").length - 1;
const doubleCount = title.split('"').length - 1;
const quote =
singleCount > doubleCount
? '"'
: doubleCount > singleCount
? "'"
: options.singleQuote
? "'"
: '"';
const { quote } = getPreferredQuote(title, options.singleQuote ? "'" : '"');
title = title.replaceAll("\\", "\\\\");
title = title.replaceAll(new RegExp(`(${quote})`, "g"), "\\$1");
return `${quote}${title}${quote}`;