Skip to content

Commit

Permalink
Improve performance (#54)
Browse files Browse the repository at this point in the history
  • Loading branch information
H4ad committed Jan 22, 2024
1 parent 210a997 commit b0dd0fa
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions index.js
Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -40,7 +43,7 @@ export default function stringWidth(string, options = {}) {
continue;
}

width += eastAsianWidth(codePoint, {ambiguousAsWide: !ambiguousIsNarrow});
width += eastAsianWidth(codePoint, eastAsianWidthOptions);
}

return width;
Expand Down

0 comments on commit b0dd0fa

Please sign in to comment.