Skip to content

Commit

Permalink
Improve performance (#49)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored May 6, 2023
1 parent 102c82c commit fe356d8
Showing 1 changed file with 6 additions and 12 deletions.
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

0 comments on commit fe356d8

Please sign in to comment.