Add MapMerge
This commit is contained in:
15
struct.go
15
struct.go
@@ -43,6 +43,21 @@ func StructHasProperty(value interface{}, name string) bool {
|
|||||||
return has
|
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.
|
// StructMustTomap given any struct return the equivalent map[string]any or nil.
|
||||||
// Will never throw.
|
// Will never throw.
|
||||||
func StructMustToMap(data any) map[string]any {
|
func StructMustToMap(data any) map[string]any {
|
||||||
|
|||||||
@@ -94,8 +94,6 @@ func TestStructToMapRecursive(t *testing.T) {
|
|||||||
default:
|
default:
|
||||||
t.Fatal("is not map")
|
t.Fatal("is not map")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMapToStruct(t *testing.T) {
|
func TestMapToStruct(t *testing.T) {
|
||||||
@@ -267,7 +265,6 @@ func TestStructHasBsonName_False(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestCopyMatching(t *testing.T) {
|
func TestCopyMatching(t *testing.T) {
|
||||||
|
|
||||||
type O struct {
|
type O struct {
|
||||||
Name string
|
Name string
|
||||||
Age int
|
Age int
|
||||||
@@ -293,5 +290,21 @@ func TestCopyMatching(t *testing.T) {
|
|||||||
if to.Name != "Nick" && to.Age != 15 && to.Active != true {
|
if to.Name != "Nick" && to.Age != 15 && to.Active != true {
|
||||||
t.Fatalf("Failed to copy matching fields to %v", to)
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user