Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: cache intl object #54

Merged
merged 1 commit into from
Jan 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
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