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

feat: add ConcatBy

This commit is contained in:
dudaodong
2024-10-24 15:38:12 +08:00
parent 2015d36b08
commit a4e89bd7c1
5 changed files with 184 additions and 0 deletions

View File

@@ -1411,3 +1411,22 @@ func JoinFunc[T any](slice []T, sep string, transform func(T) T) string {
}
return buf.String()
}
// ConcatBy concats the elements of a slice into a single value using the provided separator and connector function.
// Play: todo
func ConcatBy[T any](slice []T, sep T, connector func(T, T) T) T {
var result T
if len(slice) == 0 {
return result
}
for i, v := range slice {
result = connector(result, v)
if i < len(slice)-1 {
result = connector(result, sep)
}
}
return result
}

View File

@@ -1272,3 +1272,31 @@ func ExampleJoinFunc() {
// Output:
// A, B, C
}
func ExampleConcatBy() {
type Person struct {
Name string
Age int
}
people := []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
{Name: "Charlie", Age: 35},
}
sep := Person{Name: " | ", Age: 0}
personConnector := func(a, b Person) Person {
return Person{Name: a.Name + b.Name, Age: a.Age + b.Age}
}
result := ConcatBy(people, sep, personConnector)
fmt.Println(result.Name)
fmt.Println(result.Age)
// Output:
// Alice | Bob | Charlie
// 90
}

View File

@@ -1856,3 +1856,41 @@ func TestJoinFunc(t *testing.T) {
assert.Equal(expected, result)
})
}
func TestConcatBy(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestConcatBy")
t.Run("Join strings", func(t *testing.T) {
result := ConcatBy([]string{"Hello", "World"}, ", ", func(a, b string) string {
return a + b
})
expected := "Hello, World"
assert.Equal(expected, result)
})
t.Run("Join Person struct", func(t *testing.T) {
type Person struct {
Name string
Age int
}
people := []Person{
{Name: "Alice", Age: 30},
{Name: "Bob", Age: 25},
{Name: "Charlie", Age: 35},
}
sep := Person{Name: " | ", Age: 0}
personConnector := func(a, b Person) Person {
return Person{Name: a.Name + b.Name, Age: a.Age + b.Age}
}
result := ConcatBy(people, sep, personConnector)
assert.Equal("Alice | Bob | Charlie", result.Name)
assert.Equal(90, result.Age)
})
}