diff options
Diffstat (limited to 'internal/strutil')
-rw-r--r-- | internal/strutil/strutil.go | 10 | ||||
-rw-r--r-- | internal/strutil/strutil_test.go | 40 |
2 files changed, 50 insertions, 0 deletions
diff --git a/internal/strutil/strutil.go b/internal/strutil/strutil.go index b1de241f..30fa260a 100644 --- a/internal/strutil/strutil.go +++ b/internal/strutil/strutil.go @@ -44,3 +44,13 @@ func RandomChars(n int) (string, error) { return string(buffer), nil } + +// Ellipsis returns a truncated string and appends "..." to the end of the +// string if the string length is larger than the threshold. Otherwise, the +// original string is returned. +func Ellipsis(str string, threshold int) string { + if len(str) <= threshold || threshold < 0 { + return str + } + return str[:threshold] + "..." +} diff --git a/internal/strutil/strutil_test.go b/internal/strutil/strutil_test.go index c4edf140..8a2fed75 100644 --- a/internal/strutil/strutil_test.go +++ b/internal/strutil/strutil_test.go @@ -55,3 +55,43 @@ func TestRandomChars(t *testing.T) { cache[chars] = true } } + +func TestEllipsis(t *testing.T) { + tests := []struct { + name string + str string + threshold int + want string + }{ + { + name: "empty string and zero threshold", + str: "", + threshold: 0, + want: "", + }, + { + name: "smaller length than threshold", + str: "ab", + threshold: 3, + want: "ab", + }, + { + name: "same length as threshold", + str: "abc", + threshold: 3, + want: "abc", + }, + { + name: "greater length than threshold", + str: "ab", + threshold: 1, + want: "a...", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := Ellipsis(test.str, test.threshold) + assert.Equal(t, test.want, got) + }) + } +} |