From fe356d84abc2be9e24cbf28f2b889a412e84d86c Mon Sep 17 00:00:00 2001 From: fisker Cheung Date: Sun, 7 May 2023 03:27:30 +0800 Subject: [PATCH] Improve performance (#49) --- index.js | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index 4e95f72..62f995a 100644 --- a/index.js +++ b/index.js @@ -2,15 +2,6 @@ import stripAnsi from 'strip-ansi'; import eastAsianWidth from 'eastasianwidth'; import emojiRegex from 'emoji-regex'; -let segmenter; -function * splitString(string) { - segmenter ??= new Intl.Segmenter(); - - for (const {segment: character} of segmenter.segment(string)) { - yield character; - } -} - export default function stringWidth(string, options) { if (typeof string !== 'string' || string.length === 0) { return 0; @@ -30,12 +21,10 @@ export default function stringWidth(string, options) { return 0; } - string = string.replace(emojiRegex(), ' '); - const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2; let width = 0; - for (const character of splitString(string)) { + for (const {segment: character} of new Intl.Segmenter().segment(string)) { const codePoint = character.codePointAt(0); // Ignore control characters @@ -48,6 +37,11 @@ export default function stringWidth(string, options) { continue; } + if (emojiRegex().test(character)) { + width += 2; + continue; + } + const code = eastAsianWidth.eastAsianWidth(character); switch (code) { case 'F':