mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-08 22:52:29 +08:00
feat: add JoinFunc
This commit is contained in:
@@ -1398,3 +1398,16 @@ func Frequency[T comparable](slice []T) map[T]int {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// JoinFunc joins the slice elements into a single string with the given separator.
|
||||
// Play: todo
|
||||
func JoinFunc[T any](slice []T, sep string, transform func(T) T) string {
|
||||
var buf strings.Builder
|
||||
for i, v := range slice {
|
||||
if i > 0 {
|
||||
buf.WriteString(sep)
|
||||
}
|
||||
buf.WriteString(fmt.Sprint(transform(v)))
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
@@ -1261,3 +1261,14 @@ func ExampleFrequency() {
|
||||
// Output:
|
||||
// map[a:1 b:2 c:3]
|
||||
}
|
||||
|
||||
func ExampleJoinFunc() {
|
||||
result := JoinFunc([]string{"a", "b", "c"}, ", ", func(s string) string {
|
||||
return strings.ToUpper(s)
|
||||
})
|
||||
|
||||
fmt.Println(result)
|
||||
|
||||
// Output:
|
||||
// A, B, C
|
||||
}
|
||||
|
||||
@@ -1816,3 +1816,43 @@ func TestFrequency(t *testing.T) {
|
||||
assert.Equal(expected, result)
|
||||
})
|
||||
}
|
||||
|
||||
func TestJoinFunc(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
assert := internal.NewAssert(t, "TestJoinFunc")
|
||||
|
||||
t.Run("basic case", func(t *testing.T) {
|
||||
result := JoinFunc([]int{1, 2, 3}, ", ", func(i int) int {
|
||||
return i * 2
|
||||
})
|
||||
|
||||
expected := "2, 4, 6"
|
||||
assert.Equal(expected, result)
|
||||
})
|
||||
|
||||
t.Run("empty slice", func(t *testing.T) {
|
||||
result := JoinFunc([]int{}, ", ", func(i int) int {
|
||||
return i * 2
|
||||
})
|
||||
|
||||
assert.Equal("", result)
|
||||
})
|
||||
|
||||
t.Run("single element slice", func(t *testing.T) {
|
||||
result := JoinFunc([]int{1}, ", ", func(i int) int {
|
||||
return i * 2
|
||||
})
|
||||
|
||||
assert.Equal("2", result)
|
||||
})
|
||||
|
||||
t.Run("string slice", func(t *testing.T) {
|
||||
result := JoinFunc([]string{"a", "b", "c"}, ", ", func(s string) string {
|
||||
return strings.ToUpper(s)
|
||||
})
|
||||
|
||||
expected := "A, B, C"
|
||||
assert.Equal(expected, result)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user