From 55de9c34e8c16836e3a611bd42721e4a899db04f Mon Sep 17 00:00:00 2001 From: George Suntres Date: Wed, 22 Apr 2026 10:00:02 -0400 Subject: [PATCH] Add MapMerge --- struct.go | 15 +++++++++++++++ struct_test.go | 21 +++++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/struct.go b/struct.go index 8177797..557cd26 100644 --- a/struct.go +++ b/struct.go @@ -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 { diff --git a/struct_test.go b/struct_test.go index 152fbc0..1878553 100644 --- a/struct_test.go +++ b/struct_test.go @@ -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)) + } +} \ No newline at end of file