-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.go
49 lines (43 loc) · 959 Bytes
/
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
47
48
49
package yt
import (
"fmt"
"strings"
)
func Merge(l, r interface{}) interface{} {
lMap, lOk := l.(map[interface{}]interface{})
rMap, rOk := r.(map[interface{}]interface{})
if !(lOk && rOk) {
return r
}
for k, v := range rMap {
lMap[k] = Merge(lMap[k], v)
}
return lMap
}
func OrthogonalMerge(l, r interface{}) (interface{}, error) {
return orthogonalMergeHelper(l, r, nil)
}
func orthogonalMergeHelper(l, r interface{},
parents []string) (interface{}, error) {
lMap, lOk := l.(map[interface{}]interface{})
rMap, rOk := r.(map[interface{}]interface{})
if !(lOk && rOk) {
return nil, ErrKeyAlreadyDefined{
Key: fmt.Sprintf(".%s", strings.Join(parents, ".")),
}
}
var err error
for rk, rv := range rMap {
lv, ok := lMap[rk]
if !ok {
lMap[rk] = rv
} else {
lMap[rk], err = orthogonalMergeHelper(lv, rv,
append(parents, fmt.Sprintf("%v", rk)))
if err != nil {
return nil, err
}
}
}
return lMap, nil
}