1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 00:02:28 +08:00

feat: add Ellipsis for string

This commit is contained in:
dudaodong
2024-09-03 14:36:12 +08:00
parent 9824db0056
commit 71e914019b
5 changed files with 140 additions and 12 deletions

View File

@@ -621,6 +621,8 @@ func HammingDistance(a, b string) (int, error) {
// Concat uses the strings.Builder to concatenate the input strings.
// - `length` is the expected length of the concatenated string.
// - if you are unsure about the length of the string to be concatenated, please pass 0 or a negative number.
//
// Play: todo
func Concat(length int, str ...string) string {
if len(str) == 0 {
return ""
@@ -638,3 +640,21 @@ func Concat(length int, str ...string) string {
}
return sb.String()
}
// Ellipsis truncates a string to a specified length and appends an ellipsis.
// Play: todo
func Ellipsis(str string, length int) string {
str = strings.TrimSpace(str)
if length <= 0 {
return ""
}
runes := []rune(str)
if len(runes) <= length {
return str
}
return string(runes[:length]) + "..."
}

View File

@@ -694,3 +694,18 @@ func ExampleConcat() {
// Go Language
// An apple a daykeeps the doctor away
}
func ExampleEllipsis() {
result1 := Ellipsis("hello world", 5)
result2 := Ellipsis("你好,世界!", 2)
result3 := Ellipsis("😀😃😄😁😆", 3)
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
// Output:
// hello...
// 你好...
// 😀😃😄...
}

View File

@@ -620,3 +620,27 @@ func TestConcat(t *testing.T) {
assert.Equal("你好,世界!", Concat(0, "你好", "", "", "世界!", ""))
assert.Equal("Hello World!", Concat(0, "Hello", " Wo", "r", "ld!", ""))
}
func TestEllipsis(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestEllipsis")
tests := []struct {
input string
length int
want string
}{
{"", 0, ""},
{"hello world", 0, ""},
{"hello world", -1, ""},
{"hello world", 5, "hello..."},
{"hello world", 11, "hello world"},
{"你好,世界!", 2, "你好..."},
{"😀😃😄😁😆", 3, "😀😃😄..."},
{"This is a test.", 10, "This is a ..."},
}
for _, tt := range tests {
assert.Equal(tt.want, Ellipsis(tt.input, tt.length))
}
}