lib/stringsutil: add tests for LimitStringLen() function

This commit is contained in:
Aliaksandr Valialkin 2023-11-13 10:32:26 +01:00
parent 4722b70c89
commit 6340911d38
No known key found for this signature in database
GPG Key ID: A72BEC6CD3D0DED1
2 changed files with 28 additions and 4 deletions

View File

@ -5,12 +5,12 @@ package stringsutil
// If len(s) > maxLen, then s is replaced with "s_prefix..s_suffix",
// so the total length of the returned string doesn't exceed maxLen.
func LimitStringLen(s string, maxLen int) string {
if len(s) <= maxLen || maxLen < 4 {
if maxLen < 4 {
maxLen = 4
}
if len(s) <= maxLen {
return s
}
n := (maxLen / 2) - 1
if n < 0 {
n = 0
}
return s[:n] + ".." + s[len(s)-n:]
}

View File

@ -0,0 +1,24 @@
package stringsutil
import (
"testing"
)
func TestLimitStringLen(t *testing.T) {
f := func(s string, maxLen int, resultExpected string) {
t.Helper()
result := LimitStringLen(s, maxLen)
if result != resultExpected {
t.Fatalf("unexpected result; got %q; want %q", result, resultExpected)
}
}
f("", 1, "")
f("a", 10, "a")
f("abc", 2, "abc")
f("abcd", 3, "abcd")
f("abcde", 3, "a..e")
f("abcde", 4, "a..e")
f("abcde", 5, "abcde")
}