From b0dd0fa0a955f0c3b6e8b6b547bf0c829bdf3d06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vinicius=20Louren=C3=A7o?= <12551007+H4ad@users.noreply.github.com> Date: Mon, 22 Jan 2024 06:38:55 -0300 Subject: [PATCH] Improve performance (#54) --- index.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 4e6906e..c057dec 100644 --- a/index.js +++ b/index.js @@ -2,6 +2,8 @@ import stripAnsi from 'strip-ansi'; import {eastAsianWidth} from 'get-east-asian-width'; import emojiRegex from 'emoji-regex'; +const segmenter = new Intl.Segmenter(); + export default function stringWidth(string, options = {}) { if (typeof string !== 'string' || string.length === 0) { return 0; @@ -21,8 +23,9 @@ export default function stringWidth(string, options = {}) { } let width = 0; + const eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow}; - for (const {segment: character} of new Intl.Segmenter().segment(string)) { + for (const {segment: character} of segmenter.segment(string)) { const codePoint = character.codePointAt(0); // Ignore control characters @@ -40,7 +43,7 @@ export default function stringWidth(string, options = {}) { continue; } - width += eastAsianWidth(codePoint, {ambiguousAsWide: !ambiguousIsNarrow}); + width += eastAsianWidth(codePoint, eastAsianWidthOptions); } return width;