diff options
author | Joe Chen <jc@unknwon.io> | 2022-11-27 15:19:44 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-11-27 15:19:44 +0800 |
commit | 13099a7e4fe7565bb858646d42d1fba817cb06cc (patch) | |
tree | ac932d0f5df9f14b0f9408c32f699ae7167edc25 /internal/strutil | |
parent | a7dbc970dfaac9f04addf05da97bb0aa29083e37 (diff) |
refactor(db): add `Users.Update` (#7263)
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) + }) + } +} |