From 1a436aeb4188d9acfdab5efc6fbdf05d834fd471 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Wed, 30 Mar 2022 18:06:22 +0800 Subject: [PATCH] feat: add Merge func --- maputil/map.go | 13 +++++++++++++ maputil/map_test.go | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/maputil/map.go b/maputil/map.go index c5834e2..98f803c 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -25,3 +25,16 @@ func Values[K comparable, V any](m map[K]V) []V { return values } + +// Merge maps, next key will overwrite previous key +func Merge[K comparable, V any](maps ...map[K]V) map[K]V { + res := make(map[K]V, 0) + + for _, m := range maps { + for k, v := range m { + res[k] = v + } + } + + return res +} diff --git a/maputil/map_test.go b/maputil/map_test.go index 98cf5fa..54259f1 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -40,3 +40,25 @@ func TestValues(t *testing.T) { assert.Equal([]string{"a", "a", "b", "c", "d"}, values) } + +func TestMerge(t *testing.T) { + assert := internal.NewAssert(t, "TestMerge") + + m1 := map[int]string{ + 1: "a", + 2: "b", + } + m2 := map[int]string{ + 1: "1", + 3: "2", + } + + expected := map[int]string{ + 1: "1", + 2: "b", + 3: "2", + } + acturl := Merge(m1, m2) + + assert.Equal(expected, acturl) +}