fix(perf): shortcut getStringWidth for ASCII-only strings (#4776) (#4790)

master
Ivan Babak 2018-07-01 19:47:55 -07:00 committed by Christopher Chedeau
parent c4be0a57c3
commit 95cc2c97b5
2 changed files with 11 additions and 3 deletions

View File

@ -6,6 +6,9 @@ const escapeStringRegexp = require("escape-string-regexp");
const getCjkRegex = require("cjk-regex");
const getUnicodeRegex = require("unicode-regex");
// eslint-disable-next-line no-control-regex
const notAsciiRegex = /[^\x20-\x7F]/;
const cjkPattern = getCjkRegex().source;
// http://spec.commonmark.org/0.25/#ascii-punctuation-character
@ -713,6 +716,11 @@ function getStringWidth(text) {
return 0;
}
// shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
if (!notAsciiRegex.test(text)) {
return text.length;
}
// emojis are considered 2-char width for consistency
// see https://github.com/sindresorhus/string-width/issues/11
// for the reason why not implemented in `string-width`

View File

@ -1,6 +1,6 @@
"use strict";
const util = require("../common/util");
const { getStringWidth } = require("../common/util");
const { concat, fill, cursor } = require("./doc-builders");
/** @type {{[groupId: PropertyKey]: MODE}} */
@ -130,7 +130,7 @@ function fits(next, restCommands, width, options, mustBeFlat) {
const doc = x[2];
if (typeof doc === "string") {
width -= util.getStringWidth(doc);
width -= getStringWidth(doc);
} else {
switch (doc.type) {
case "concat":
@ -224,7 +224,7 @@ function printDocToString(doc, options) {
if (typeof doc === "string") {
out.push(doc);
pos += util.getStringWidth(doc);
pos += getStringWidth(doc);
} else {
switch (doc.type) {
case "cursor":