From 993b0e6023b9dac6ef241232568a8536ad7363e9 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Thu, 27 Jul 2023 20:14:57 +0800 Subject: [PATCH] feat: add Join --- docs/slice.md | 34 ++++++++++++++++++++++++++++++++++ docs/slice_zh-CN.md | 35 +++++++++++++++++++++++++++++++++++ slice/slice.go | 13 +++++++++++++ slice/slice_test.go | 12 ++++++++++++ 4 files changed, 94 insertions(+) diff --git a/docs/slice.md b/docs/slice.md index 867cee2..5b91366 100644 --- a/docs/slice.md +++ b/docs/slice.md @@ -62,6 +62,7 @@ import ( - [Union](#Union) - [UpdateByIndex](#UpdateByIndex) - [Without](#Without) +- [Join](#Join)
@@ -1172,3 +1173,36 @@ func main() { fmt.Println(res) //[]int{3, 4, 5} } ``` + +### Join + +

Join the slice item with specify separator.

+ +Signature: + +```go +func Join(slice interface{}, separator string) string +``` + +Example: + +```go +import ( + "fmt" + "github.com/duke-git/lancet/slice" +) + +func main() { + nums := []int{1, 2, 3, 4, 5} + + result1 := slice.Join(nums, ",") + result2 := slice.Join(nums, "-") + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 1,2,3,4,5 + // 1-2-3-4-5 +} +``` diff --git a/docs/slice_zh-CN.md b/docs/slice_zh-CN.md index 01849c2..2bc1a28 100644 --- a/docs/slice_zh-CN.md +++ b/docs/slice_zh-CN.md @@ -62,6 +62,8 @@ import ( - [Union](#Union) - [UpdateByIndex](#UpdateByIndex) - [Without](#Without) +- [Join](#Join) +
@@ -1168,3 +1170,36 @@ func main() { fmt.Println(res) //[]int{3, 4, 5} } ``` + +### Join + +

用指定的分隔符链接切片元素。

+ +函数签名: + +```go +func Join(slice interface{}, separator string) string +``` + +示例: + +```go +import ( + "fmt" + "github.com/duke-git/lancet/slice" +) + +func main() { + nums := []int{1, 2, 3, 4, 5} + + result1 := slice.Join(nums, ",") + result2 := slice.Join(nums, "-") + + fmt.Println(result1) + fmt.Println(result2) + + // Output: + // 1,2,3,4,5 + // 1-2-3-4-5 +} +``` diff --git a/slice/slice.go b/slice/slice.go index 88f5fe8..d0ad29a 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -968,3 +968,16 @@ func AppendIfAbsent(slice interface{}, value interface{}) interface{} { } return out.Interface() } + +// AppendIfAbsent only absent append the value +func Join(slice interface{}, separator string) string { + sv := sliceValue(slice) + + strs := make([]string, sv.Len()) + + for i := 0; i < sv.Len(); i++ { + strs[i] = fmt.Sprint(sv.Index(i).Interface()) + } + + return strings.Join(strs, separator) +} diff --git a/slice/slice_test.go b/slice/slice_test.go index 649fe61..d950be2 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -624,3 +624,15 @@ func TestAppendIfAbsent(t *testing.T) { assert.Equal([]string{"a", "b"}, AppendIfAbsent(str1, "a")) assert.Equal([]string{"a", "b", "c"}, AppendIfAbsent(str1, "c")) } + +func TestJoin(t *testing.T) { + assert := internal.NewAssert(t, "TestJoin") + + nums := []int{1, 2, 3, 4, 5} + + result1 := Join(nums, ",") + result2 := Join(nums, "-") + + assert.Equal("1,2,3,4,5", result1) + assert.Equal("1-2-3-4-5", result2) +}