Skip to content

Commit

Permalink
feat: collection 包新增 MergeSlice 函数,用于将多个同类型对象合并为一个切片
Browse files Browse the repository at this point in the history
  • Loading branch information
kercylan98 committed Jan 30, 2024
1 parent e585e12 commit 4799a8c
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
11 changes: 11 additions & 0 deletions utils/collection/merge.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
package collection

// MergeSlice 合并切片
func MergeSlice[V any](values ...V) (result []V) {
if len(values) == 0 {
return nil
}

result = make([]V, 0, len(values))
result = append(result, values...)
return
}

// MergeSlices 合并切片
func MergeSlices[S ~[]V, V any](slices ...S) (result S) {
if len(slices) == 0 {
Expand Down
6 changes: 6 additions & 0 deletions utils/collection/merge_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import (
"github.com/kercylan98/minotaur/utils/collection"
)

func ExampleMergeSlice() {
fmt.Println(collection.MergeSlice(1, 2, 3))
// Output:
// [1 2 3]
}

func ExampleMergeSlices() {
fmt.Println(
collection.MergeSlices(
Expand Down
25 changes: 25 additions & 0 deletions utils/collection/merge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,31 @@ import (
"testing"
)

func TestMergeSlice(t *testing.T) {
var cases = []struct {
name string
input []int
expected []int
}{
{"TestMergeSlice_NonEmptySlice", []int{1, 2, 3}, []int{1, 2, 3}},
{"TestMergeSlice_EmptySlice", []int{}, []int{}},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
result := collection.MergeSlice(c.input...)
if len(result) != len(c.expected) {
t.Fatalf("%s failed, expected: %v, actual: %v, error: %s", c.name, c.expected, result, "the length of input is not equal")
}
for i := 0; i < len(result); i++ {
if result[i] != c.expected[i] {
t.Fatalf("%s failed, expected: %v, actual: %v, error: %s", c.name, c.expected, result, "the value of input is not equal")
}
}
})
}
}

func TestMergeSlices(t *testing.T) {
var cases = []struct {
name string
Expand Down

0 comments on commit 4799a8c

Please sign in to comment.