-
Notifications
You must be signed in to change notification settings - Fork 0
/
texts.go
50 lines (42 loc) · 1.14 KB
/
texts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Package texts provides string truncation.
package texts
import (
"unicode"
"unicode/utf8"
)
// Truncate shortens text until the length of the shortened text and appended
// suffix is equal to or less than maxLength. If exact is true, text is cut
// mid-word.
func Truncate(text string, maxLength int, suffix string, exact bool) string {
if utf8.RuneCountInString(text) <= maxLength {
return text
}
suffixLength := utf8.RuneCountInString(suffix)
if suffixLength > maxLength {
return ""
}
truncatedText := make([]rune, 0, maxLength)
if exact {
maxLengthWithoutSuffix := maxLength - suffixLength
for _, character := range text {
if len(truncatedText) == maxLengthWithoutSuffix {
break
}
truncatedText = append(truncatedText, character)
}
} else {
word := []rune{}
for _, character := range text {
word = append(word, character)
if unicode.IsSpace(character) {
if len(truncatedText)+len(word)+suffixLength > maxLength {
break
}
truncatedText = append(truncatedText, word...)
word = []rune{}
}
}
}
truncatedText = append(truncatedText, []rune(suffix)...)
return string(truncatedText)
}