feat: collection 包新增 MergeSlice 函数,用于将多个同类型对象合并为一个切片
This commit is contained in:
parent
e585e12a72
commit
4799a8cb73
|
@ -1,5 +1,16 @@
|
||||||
package collection
|
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 合并切片
|
// MergeSlices 合并切片
|
||||||
func MergeSlices[S ~[]V, V any](slices ...S) (result S) {
|
func MergeSlices[S ~[]V, V any](slices ...S) (result S) {
|
||||||
if len(slices) == 0 {
|
if len(slices) == 0 {
|
||||||
|
|
|
@ -5,6 +5,12 @@ import (
|
||||||
"github.com/kercylan98/minotaur/utils/collection"
|
"github.com/kercylan98/minotaur/utils/collection"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func ExampleMergeSlice() {
|
||||||
|
fmt.Println(collection.MergeSlice(1, 2, 3))
|
||||||
|
// Output:
|
||||||
|
// [1 2 3]
|
||||||
|
}
|
||||||
|
|
||||||
func ExampleMergeSlices() {
|
func ExampleMergeSlices() {
|
||||||
fmt.Println(
|
fmt.Println(
|
||||||
collection.MergeSlices(
|
collection.MergeSlices(
|
||||||
|
|
|
@ -5,6 +5,31 @@ import (
|
||||||
"testing"
|
"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) {
|
func TestMergeSlices(t *testing.T) {
|
||||||
var cases = []struct {
|
var cases = []struct {
|
||||||
name string
|
name string
|
||||||
|
|
Loading…
Reference in New Issue