Add MapMerge

This commit is contained in:
George Suntres
2026-04-22 10:00:02 -04:00
parent f0bb6adf71
commit 55de9c34e8
2 changed files with 32 additions and 4 deletions

View File

@@ -43,6 +43,21 @@ func StructHasProperty(value interface{}, name string) bool {
return has
}
// MapMerge merges maps into one.
func MapMerge[T ~map[string]any](maps...T) T {
out := make(T)
for _, m := range maps {
if m != nil {
for k, v := range m {
out[k] = v
}
}
}
return out
}
// StructMustTomap given any struct return the equivalent map[string]any or nil.
// Will never throw.
func StructMustToMap(data any) map[string]any {

View File

@@ -94,8 +94,6 @@ func TestStructToMapRecursive(t *testing.T) {
default:
t.Fatal("is not map")
}
}
func TestMapToStruct(t *testing.T) {
@@ -267,7 +265,6 @@ func TestStructHasBsonName_False(t *testing.T) {
}
func TestCopyMatching(t *testing.T) {
type O struct {
Name string
Age int
@@ -293,5 +290,21 @@ func TestCopyMatching(t *testing.T) {
if to.Name != "Nick" && to.Age != 15 && to.Active != true {
t.Fatalf("Failed to copy matching fields to %v", to)
}
}
func TestMapMerge(t *testing.T) {
m1 := map[string]any{
"a": "va",
"b": "vb",
}
m2 := map[string]any{
"c": "vc",
"d": "vd",
}
m := MapMerge(m1, m2)
if len(m) != 4 {
t.Fatalf("Merged map should have lenght 4 not %d", len(m))
}
}