-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
82 lines (62 loc) · 1.28 KB
/
map.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package funcs
import (
"strings"
"sync"
"github.com/rytsh/liz/fstore/generic"
)
func init() {
generic.CallReg.AddFunction("map", new(Map).init)
}
type Map struct {
value map[string]interface{}
mutex sync.RWMutex
}
func (m *Map) init() *Map {
if m.value == nil {
m.value = make(map[string]interface{})
}
return m
}
func (m *Map) Set(key string, value interface{}) map[string]interface{} {
m.mutex.Lock()
defer m.mutex.Unlock()
// separate key with / to create nested map
vKey := strings.Split(key, "/")
hWalk := m.value
for i, v := range vKey {
if i == len(vKey)-1 {
hWalk[v] = value
break
}
if _, ok := hWalk[v]; !ok {
hWalk[v] = make(map[string]interface{})
}
if _, ok := hWalk[v].(map[string]interface{}); !ok {
hWalk[v] = make(map[string]interface{})
}
hWalk = hWalk[v].(map[string]interface{})
}
return m.value
}
func (m *Map) Get(key string, data map[string]interface{}) interface{} {
m.mutex.RLock()
defer m.mutex.RUnlock()
if data == nil {
data = m.value
}
keyValues := strings.Split(key, "/")
for i, v := range keyValues {
if _, ok := data[v]; !ok {
return nil
}
if i == len(keyValues)-1 {
return data[v]
}
var ok bool
data, ok = data[v].(map[string]interface{})
if !ok {
return nil
}
}
return nil
}