diff options
Diffstat (limited to 'internal/strutil')
-rw-r--r-- | internal/strutil/strutil.go | 9 | ||||
-rw-r--r-- | internal/strutil/strutil_test.go | 40 |
2 files changed, 49 insertions, 0 deletions
diff --git a/internal/strutil/strutil.go b/internal/strutil/strutil.go index 30fa260a..c1013959 100644 --- a/internal/strutil/strutil.go +++ b/internal/strutil/strutil.go @@ -54,3 +54,12 @@ func Ellipsis(str string, threshold int) string { } return str[:threshold] + "..." } + +// Truncate returns a truncated string if its length is over the limit. +// Otherwise, it returns the original string. +func Truncate(str string, limit int) string { + if len(str) < limit { + return str + } + return str[:limit] +} diff --git a/internal/strutil/strutil_test.go b/internal/strutil/strutil_test.go index 8a2fed75..d22e1f72 100644 --- a/internal/strutil/strutil_test.go +++ b/internal/strutil/strutil_test.go @@ -95,3 +95,43 @@ func TestEllipsis(t *testing.T) { }) } } + +func TestTruncate(t *testing.T) { + tests := []struct { + name string + str string + limit int + want string + }{ + { + name: "empty string with zero limit", + str: "", + limit: 0, + want: "", + }, + { + name: "smaller length than limit", + str: "ab", + limit: 3, + want: "ab", + }, + { + name: "same length as limit", + str: "abc", + limit: 3, + want: "abc", + }, + { + name: "greater length than limit", + str: "ab", + limit: 1, + want: "a", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := Truncate(test.str, test.limit) + assert.Equal(t, test.want, got) + }) + } +} |