Skip to content

Commit 5597a47

Browse files
committed
Make trimLongString more robust
1 parent 406f249 commit 5597a47

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

src/app/utils/trimLongString.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
1+
/**
2+
* Get a shortened version of a string
3+
*
4+
* @param value The original string
5+
* @param trimStart How many characters to use at the beginning? (Minimum: 1)
6+
* @param trimEnd How many characters to use at the end? (Minimum: 0)
7+
* @param ellipsis What string should we use to indicate the shortening?
8+
*/
19
export function trimLongString(value: string, trimStart = 6, trimEnd = 6, ellipsis = '…') {
2-
if (!value) {
3-
return
4-
}
5-
const trimmedLength = trimStart + ellipsis.length + trimEnd
6-
if (trimmedLength > value.length) {
7-
return value
8-
}
10+
if (!value) return
11+
// We always want to show at least one character at the beginning and at the end
12+
const wantedStart = Math.max(trimStart, 1)
13+
// We might not want to show anything from the end of the string, but the number should not be negative
14+
const wantedEnd = Math.max(trimEnd, 0)
15+
const trimmedLength = wantedStart + ellipsis.length + wantedEnd
16+
if (trimmedLength > value.length) return value
917

10-
return `${value.slice(0, trimStart)}${ellipsis}${trimEnd ? value.slice(-trimEnd) : ''}`
18+
return `${value.slice(0, wantedStart)}${ellipsis}${trimEnd ? value.slice(-wantedEnd) : ''}`
1119
}

0 commit comments

Comments
 (0)