From 1af8fe8dafa799cb289a48e7609d7ae5827e44f6 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 30 Mar 2022 17:45:17 +0800 Subject: [PATCH] test: add unit test for Keys and Values func --- maputil/map.go | 4 ++-- maputil/map_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 maputil/map_test.go diff --git a/maputil/map.go b/maputil/map.go index 035b4ad..c5834e2 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -6,7 +6,7 @@ package maputil // Keys returns a slice of the map's keys func Keys[K comparable, V any](m map[K]V) []K { - keys := make([]K, len(m)) + keys := make([]K, 0, len(m)) for k := range m { keys = append(keys, k) @@ -17,7 +17,7 @@ func Keys[K comparable, V any](m map[K]V) []K { // Values returns a slice of the map's values func Values[K comparable, V any](m map[K]V) []V { - values := make([]V, len(m)) + values := make([]V, 0, len(m)) for _, v := range m { values = append(values, v) diff --git a/maputil/map_test.go b/maputil/map_test.go new file mode 100644 index 0000000..98cf5fa --- /dev/null +++ b/maputil/map_test.go @@ -0,0 +1,42 @@ +package maputil + +import ( + "sort" + "testing" + + "github.com/duke-git/lancet/v2/internal" +) + +func TestKeys(t *testing.T) { + assert := internal.NewAssert(t, "TestKeys") + + m := map[int]string{ + 1: "a", + 2: "a", + 3: "b", + 4: "c", + 5: "d", + } + + keys := Keys(m) + sort.Ints(keys) + + assert.Equal([]int{1, 2, 3, 4, 5}, keys) +} + +func TestValues(t *testing.T) { + assert := internal.NewAssert(t, "TestValues") + + m := map[int]string{ + 1: "a", + 2: "a", + 3: "b", + 4: "c", + 5: "d", + } + + values := Values(m) + sort.Strings(values) + + assert.Equal([]string{"a", "a", "b", "c", "d"}, values) +}