From 4799a8cb73d2bccb2b8a1fd0b33bc2a9746a3f89 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Tue, 30 Jan 2024 12:38:38 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20collection=20=E5=8C=85=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=20MergeSlice=20=E5=87=BD=E6=95=B0=EF=BC=8C=E7=94=A8?= =?UTF-8?q?=E4=BA=8E=E5=B0=86=E5=A4=9A=E4=B8=AA=E5=90=8C=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=AF=B9=E8=B1=A1=E5=90=88=E5=B9=B6=E4=B8=BA=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=88=87=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/collection/merge.go | 11 +++++++++++ utils/collection/merge_example_test.go | 6 ++++++ utils/collection/merge_test.go | 25 +++++++++++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/utils/collection/merge.go b/utils/collection/merge.go index f0f78f30..1d6ee509 100644 --- a/utils/collection/merge.go +++ b/utils/collection/merge.go @@ -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 { diff --git a/utils/collection/merge_example_test.go b/utils/collection/merge_example_test.go index 83191524..bf34c43f 100644 --- a/utils/collection/merge_example_test.go +++ b/utils/collection/merge_example_test.go @@ -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( diff --git a/utils/collection/merge_test.go b/utils/collection/merge_test.go index ea31c64e..46ce9be8 100644 --- a/utils/collection/merge_test.go +++ b/utils/collection/merge_test.go @@ -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