Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement lo.Join #373

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lo

import (
"fmt"
"math/rand"

"golang.org/x/exp/constraints"
Expand Down Expand Up @@ -592,3 +593,19 @@ func IsSortedByKey[T any, K constraints.Ordered](collection []T, iteratee func(i

return true
}

// Join converts all elements in array into a string separated by separator.
func Join[T any](collection []T, separator string) string {
size := len(collection)
result := ""

for i := 0; i < size; i++ {
if i == size-1 {
result += fmt.Sprintf("%v", collection[i])
} else {
result += fmt.Sprintf("%v%v", collection[i], separator)
}
}

return result
}
19 changes: 17 additions & 2 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ func TestAssociate(t *testing.T) {

func TestSliceToMap(t *testing.T) {
t.Parallel()

type foo struct {
baz string
bar int
Expand Down Expand Up @@ -626,7 +626,7 @@ func TestSlice(t *testing.T) {
out16 := Slice(in, -10, 1)
out17 := Slice(in, -1, 3)
out18 := Slice(in, -10, 7)

is.Equal([]int{}, out1)
is.Equal([]int{0}, out2)
is.Equal([]int{0, 1, 2, 3, 4}, out3)
Expand Down Expand Up @@ -759,3 +759,18 @@ func TestIsSortedByKey(t *testing.T) {
return ret
}))
}

func TestJoin(t *testing.T) {
t.Parallel()
is := assert.New(t)

r1 := Join([]int{1, 2, 3}, "-")
r2 := Join([]float64{1.1, 2.2, 3.3}, "-")
r3 := Join([]bool{true, false}, "-")
r4 := Join([]string{"a", "b", "c"}, "-")

is.Equal(r1, "1-2-3")
is.Equal(r2, "1.1-2.2-3.3")
is.Equal(r3, "true-false")
is.Equal(r4, "a-b-c")
}