diff --git a/modules/common/util/map.go b/modules/common/util/map.go index 056980f9..c990ed65 100644 --- a/modules/common/util/map.go +++ b/modules/common/util/map.go @@ -80,3 +80,22 @@ func SortStringMapByValue(in map[string]string) List { return sorted } + +// MergeMaps - merge two or more maps +// NOTE: In case a key exists, the value in the first map is preserved. +func MergeMaps[K comparable, V any](baseMap map[K]V, extraMaps ...map[K]V) map[K]V { + mergedMap := make(map[K]V) + for key, value := range baseMap { + mergedMap[key] = value + } + + for _, extraMap := range extraMaps { + for key, value := range extraMap { + if _, ok := mergedMap[key]; !ok { + mergedMap[key] = value + } + } + } + + return mergedMap +} diff --git a/modules/common/util/map_test.go b/modules/common/util/map_test.go index 14a85cd8..db8bffe2 100644 --- a/modules/common/util/map_test.go +++ b/modules/common/util/map_test.go @@ -92,3 +92,44 @@ func TestSortStringMapByValue(t *testing.T) { g.Expect(l[1]).To(HaveField("Value", "b")) }) } + +func TestMergeMaps(t *testing.T) { + t.Run("Merge maps", func(t *testing.T) { + g := NewWithT(t) + + m1 := map[string]string{ + "a": "a", + } + m2 := map[string]string{ + "b": "b", + "c": "c", + } + + mergedIntMap := MergeMaps(m1, m2) + + g.Expect(mergedIntMap).To(HaveKeyWithValue("a", "a")) + g.Expect(mergedIntMap).To(HaveKeyWithValue("b", "b")) + g.Expect(mergedIntMap).To(HaveKeyWithValue("c", "c")) + }) + + t.Run("Merge maps with existing key, the value in the first map is preserved", func(t *testing.T) { + g := NewWithT(t) + + m1 := map[string]int{ + "a": 2, + "b": 2, + } + + m2 := map[string]int{ + "a": 2, + "c": 3, + "b": 4, + } + + mergedIntMap := MergeMaps(m1, m2) + + g.Expect(mergedIntMap).To(HaveKeyWithValue("a", 2)) + g.Expect(mergedIntMap).To(HaveKeyWithValue("b", 2)) + g.Expect(mergedIntMap).To(HaveKeyWithValue("c", 3)) + }) +}