GoDict/dict/dict.go

134 lines
2.2 KiB
Go

package dict
import (
"fmt"
"strings"
)
type Dict map[string]interface{}
func New() Dict {
return make(Dict)
}
func IsDict(a interface{}) bool {
_, ok := a.(Dict)
return ok
}
func (d Dict) HasKey(key string) bool {
_, ok := d[key]
return ok
}
func (d Dict) Print() {
pp, err := d.DumpJsonStrIndent("", " ")
if err != nil {
panic(err)
}
fmt.Println(pp)
}
func (d Dict) GetInheritedValueAll(path string) Dict {
var value Dict
current := make(Dict)
g := make(Dict)
current.CopyFrom(d)
keys := strings.Split(path, ".")
lastIndex := len(keys) - 1
for i, key := range keys {
if current.HasKey("globals") {
g.MergeWith(current["globals"].(Dict))
current.SoftMergeWith(g)
}
if !current.HasKey(key) {
break
}
v := current[key]
if i == lastIndex {
if vv, ok := v.(Dict); ok {
vv.SoftMergeWith(g)
value = vv
} else {
value = Dict{"value": v}
}
break
}
if IsDict(v) {
current = v.(Dict)
} else {
break
}
}
return value
}
func (d Dict) GetInheritedValue(path string) Dict {
var value Dict
current := make(Dict)
g := make(Dict)
current.CopyFrom(d)
keys := strings.Split(path, ".")
lastIndex := len(keys) - 1
for i, key := range keys {
if current.HasKey("globals") {
g.MergeWith(current["globals"].(Dict))
current.SoftMergeWith(g)
}
if !current.HasKey(key) {
break
}
v := current[key]
if i == lastIndex {
if vv, ok := v.(Dict); ok {
if g.HasKey(key) {
if gv, ok := g[key].(Dict); ok {
vv.SoftMergeWith(gv)
value = vv
}
} else {
vv.SoftMergeWith(g)
value = vv
}
} else {
value = Dict{"value": v}
}
break
}
if IsDict(v) {
current = v.(Dict)
} else {
break
}
}
return value
}
func (d Dict) GetDirectValue(path string) Dict {
var value Dict
current := make(Dict)
current.CopyFrom(d)
keys := strings.Split(path, ".")
lastIndex := len(keys) - 1
for i, key := range keys {
if !current.HasKey(key) {
break
}
v := current[key]
if i == lastIndex {
if vv, ok := v.(Dict); ok {
value = vv
} else {
value = Dict{"value": v}
}
break
}
if IsDict(v) {
current = v.(Dict)
} else {
break
}
}
return value
}