Skip to content

Commit e02467e

Browse files
authored
fix: support inspect on strings with unicode (#79)
* Support inspect on strings with unicode * Update src/helpers.ts * fix lint
1 parent 9b8a6de commit e02467e

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/helpers.ts

+9-1
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,10 @@ export function normaliseOptions(
9393
return options
9494
}
9595

96+
function isHighSurrogate(char: string): boolean {
97+
return char >= '\ud800' && char <= '\udbff'
98+
}
99+
96100
export function truncate(string: string | number, length: number, tail: typeof truncator = truncator) {
97101
string = String(string)
98102
const tailLength = tail.length
@@ -101,7 +105,11 @@ export function truncate(string: string | number, length: number, tail: typeof t
101105
return tail
102106
}
103107
if (stringLength > length && stringLength > tailLength) {
104-
return `${string.slice(0, length - tailLength)}${tail}`
108+
let end = length - tailLength
109+
if (end > 0 && isHighSurrogate(string[end - 1])) {
110+
end = end - 1
111+
}
112+
return `${string.slice(0, end)}${tail}`
105113
}
106114
return string
107115
}

test/strings.js

+19
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,25 @@ describe('strings', () => {
5959
expect(inspect('foobarbaz', { truncate: 3 })).to.equal("'…'")
6060
})
6161

62+
it('truncates strings involving surrogate pairs longer than truncate (7)', () => {
63+
// not '🐱🐱\ud83d…' (length 7) but '🐱🐱…' (length 6)
64+
expect(inspect('🐱🐱🐱', { truncate: 7 })).to.equal("'🐱🐱…'")
65+
})
66+
67+
it('truncates strings involving surrogate pairs longer than truncate (6)', () => {
68+
expect(inspect('🐱🐱🐱', { truncate: 6 })).to.equal("'🐱…'")
69+
})
70+
71+
it('truncates strings involving surrogate pairs longer than truncate (5)', () => {
72+
// not '🐱\ud83d…' (length 5) but '🐱…' (length 4)
73+
expect(inspect('🐱🐱🐱', { truncate: 5 })).to.equal("'🐱…'")
74+
})
75+
76+
it('truncates strings involving graphemes than truncate (5)', () => {
77+
// partial support: valid string for unicode
78+
expect(inspect('👨‍👩‍👧‍👧', { truncate: 5 })).to.equal("'👨…'")
79+
})
80+
6281
it('disregards truncate when it cannot truncate further (2)', () => {
6382
expect(inspect('foobarbaz', { truncate: 2 })).to.equal("'…'")
6483
})

0 commit comments

Comments
 (0)