Skip to content

Commit

Permalink
Merge pull request #397 from stuggi/mergemaps
Browse files Browse the repository at this point in the history
[util] add generic MergeMaps func
  • Loading branch information
stuggi authored Nov 21, 2023
2 parents 853ac40 + b610ebe commit 551c0ac
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
19 changes: 19 additions & 0 deletions modules/common/util/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
41 changes: 41 additions & 0 deletions modules/common/util/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
}

0 comments on commit 551c0ac

Please sign in to comment.