forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_reduce.go
52 lines (41 loc) · 1.13 KB
/
merge_reduce.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
50
51
52
package generic
func Merge(collection, otherCollection Map) Map {
mergedMap := NewMap()
iterator := func(key, value interface{}) {
mergedMap.Set(key, value)
}
Each(collection, iterator)
Each(otherCollection, iterator)
return mergedMap
}
func DeepMerge(maps ...Map) Map {
mergedMap := NewMap()
return Reduce(maps, mergedMap, mergeReducer)
}
func mergeReducer(key, val interface{}, reduced Map) Map {
switch {
case reduced.Has(key) == false:
reduced.Set(key, val)
return reduced
case IsMappable(val):
maps := []Map{NewMap(reduced.Get(key)), NewMap(val)}
mergedMap := Reduce(maps, NewMap(), mergeReducer)
reduced.Set(key, mergedMap)
return reduced
case IsSliceable(val):
reduced.Set(key, append(reduced.Get(key).([]interface{}), val.([]interface{})...))
return reduced
default:
reduced.Set(key, val)
return reduced
}
}
type Reducer func(key, val interface{}, reducedVal Map) Map
func Reduce(collections []Map, resultVal Map, cb Reducer) Map {
for _, collection := range collections {
for _, key := range collection.Keys() {
resultVal = cb(key, collection.Get(key), resultVal)
}
}
return resultVal
}