Skip to content

Commit fe356d8

Browse files
authored
Improve performance (#49)
1 parent 102c82c commit fe356d8

File tree

1 file changed

+6
-12
lines changed

1 file changed

+6
-12
lines changed

index.js

+6-12
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,6 @@ import stripAnsi from 'strip-ansi';
22
import eastAsianWidth from 'eastasianwidth';
33
import emojiRegex from 'emoji-regex';
44

5-
let segmenter;
6-
function * splitString(string) {
7-
segmenter ??= new Intl.Segmenter();
8-
9-
for (const {segment: character} of segmenter.segment(string)) {
10-
yield character;
11-
}
12-
}
13-
145
export default function stringWidth(string, options) {
156
if (typeof string !== 'string' || string.length === 0) {
167
return 0;
@@ -30,12 +21,10 @@ export default function stringWidth(string, options) {
3021
return 0;
3122
}
3223

33-
string = string.replace(emojiRegex(), ' ');
34-
3524
const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;
3625
let width = 0;
3726

38-
for (const character of splitString(string)) {
27+
for (const {segment: character} of new Intl.Segmenter().segment(string)) {
3928
const codePoint = character.codePointAt(0);
4029

4130
// Ignore control characters
@@ -48,6 +37,11 @@ export default function stringWidth(string, options) {
4837
continue;
4938
}
5039

40+
if (emojiRegex().test(character)) {
41+
width += 2;
42+
continue;
43+
}
44+
5145
const code = eastAsianWidth.eastAsianWidth(character);
5246
switch (code) {
5347
case 'F':

0 commit comments

Comments
 (0)