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

Improve performance #49

Merged
merged 1 commit into from
May 6, 2023
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
18 changes: 6 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -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':
Expand Down