Skip to content

Commit

Permalink
fix: support inspect on strings with unicode (#79)
Browse files Browse the repository at this point in the history
* Support inspect on strings with unicode

* Update src/helpers.ts

* fix lint
  • Loading branch information
dubzzz authored May 11, 2024
1 parent 9b8a6de commit e02467e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ export function normaliseOptions(
return options
}

function isHighSurrogate(char: string): boolean {
return char >= '\ud800' && char <= '\udbff'
}

export function truncate(string: string | number, length: number, tail: typeof truncator = truncator) {
string = String(string)
const tailLength = tail.length
Expand All @@ -101,7 +105,11 @@ export function truncate(string: string | number, length: number, tail: typeof t
return tail
}
if (stringLength > length && stringLength > tailLength) {
return `${string.slice(0, length - tailLength)}${tail}`
let end = length - tailLength
if (end > 0 && isHighSurrogate(string[end - 1])) {
end = end - 1
}
return `${string.slice(0, end)}${tail}`
}
return string
}
Expand Down
19 changes: 19 additions & 0 deletions test/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,25 @@ describe('strings', () => {
expect(inspect('foobarbaz', { truncate: 3 })).to.equal("'…'")
})

it('truncates strings involving surrogate pairs longer than truncate (7)', () => {
// not '🐱🐱\ud83d…' (length 7) but '🐱🐱…' (length 6)
expect(inspect('🐱🐱🐱', { truncate: 7 })).to.equal("'🐱🐱…'")
})

it('truncates strings involving surrogate pairs longer than truncate (6)', () => {
expect(inspect('🐱🐱🐱', { truncate: 6 })).to.equal("'🐱…'")
})

it('truncates strings involving surrogate pairs longer than truncate (5)', () => {
// not '🐱\ud83d…' (length 5) but '🐱…' (length 4)
expect(inspect('🐱🐱🐱', { truncate: 5 })).to.equal("'🐱…'")
})

it('truncates strings involving graphemes than truncate (5)', () => {
// partial support: valid string for unicode
expect(inspect('👨‍👩‍👧‍👧', { truncate: 5 })).to.equal("'👨…'")
})

it('disregards truncate when it cannot truncate further (2)', () => {
expect(inspect('foobarbaz', { truncate: 2 })).to.equal("'…'")
})
Expand Down

0 comments on commit e02467e

Please sign in to comment.