Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions maps/maps.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,16 @@ func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
}
}
}

// Merge returns every key/value pairs from m maps in a single map.
// The order in which arguments are passed matters,
// the last maps values will override the first ones if some key is identical
func Merge[M ~map[K]V, K comparable, V any](m ...M) M {
r := make(M)
for _, elem := range m {
for k, v := range elem {
r[k] = v
}
}
return r
}
13 changes: 13 additions & 0 deletions maps/maps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,16 @@ func TestDeleteFunc(t *testing.T) {
t.Errorf("DeleteFunc result = %v, want %v", mc, want)
}
}

func TestMerge(t *testing.T) {
m1 := map[int]int{1: 2, 2: 4, 4: 8, 8: 16}
m2 := map[int]int{3: 9, 4: 16, 5: 25, 8: 64}
m3 := map[int]int{1: 1, 4: 4, 6: 6, 7: 7}

want := map[int]int{1: 1, 2: 4, 3: 9, 4: 4, 5: 25, 6: 6, 7: 7, 8: 64}

res := Merge(m1, m2, m3)
if !Equal(res, want) {
t.Errorf("Merge(%v, %v, %v) = %v, want %v", m1, m2, m3, res, want)
}
}