-
Notifications
You must be signed in to change notification settings - Fork 126
/
merge.go
46 lines (39 loc) · 1.02 KB
/
merge.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package datautils
func isYAMLTable(v interface{}) bool {
_, ok := v.(map[string]interface{})
return ok
}
// MergeMaps merges any number of maps together, with maps later in the slice taking
// precedent
func MergeMaps(maps ...map[string]interface{}) map[string]interface{} {
// merge bottom-up
if len(maps) > 2 {
mLen := len(maps)
newMaps := maps[0 : mLen-2]
// reduce length of maps by 1 and merge again
newMaps = append(newMaps, MergeMaps(maps[mLen-2], maps[mLen-1]))
return MergeMaps(newMaps...)
} else if len(maps) == 2 {
if maps[0] == nil {
return maps[1]
}
if maps[1] == nil {
return maps[0]
}
for key, map0Val := range maps[0] {
if map1Val, ok := maps[1][key]; ok && map1Val == nil {
delete(maps[1], key)
} else if !ok {
maps[1][key] = map0Val
} else if isYAMLTable(map0Val) {
if isYAMLTable(map1Val) {
MergeMaps(map0Val.(map[string]interface{}), map1Val.(map[string]interface{}))
}
}
}
return maps[1]
} else if len(maps) == 1 {
return maps[0]
}
return nil
}