Skip to content

Commit b7d24dc

Browse files
committed
maps: add Merge function
this function allows to merge multiple generic maps in a single one
1 parent 47842c8 commit b7d24dc

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

maps/maps.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,16 @@ func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
9292
}
9393
}
9494
}
95+
96+
// Merge returns every key/value pairs from m maps in a single map.
97+
// The order in which arguments are passed matters,
98+
// the last maps values will override the first ones if some key is identical
99+
func Merge[M ~map[K]V, K comparable, V any](m ...M) M {
100+
r := make(M)
101+
for _, elem := range m {
102+
for k, v := range elem {
103+
r[k] = v
104+
}
105+
}
106+
return r
107+
}

maps/maps_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,16 @@ func TestDeleteFunc(t *testing.T) {
179179
t.Errorf("DeleteFunc result = %v, want %v", mc, want)
180180
}
181181
}
182+
183+
func TestMerge(t *testing.T) {
184+
m1 := map[int]int{1: 2, 2: 4, 4: 8, 8: 16}
185+
m2 := map[int]int{3: 9, 4: 16, 5: 25, 8: 64}
186+
m3 := map[int]int{1: 1, 4: 4, 6: 6, 7: 7}
187+
188+
want := map[int]int{1: 1, 2: 4, 3: 9, 4: 4, 5: 25, 6: 6, 7: 7, 8: 64}
189+
190+
res := Merge(m1, m2, m3)
191+
if !Equal(res, want) {
192+
t.Errorf("Merge(%v, %v, %v) = %v, want %v", m1, m2, m3, res, want)
193+
}
194+
}

0 commit comments

Comments
 (0)