-
Notifications
You must be signed in to change notification settings - Fork 0
/
orderedmap.go
91 lines (66 loc) · 1.43 KB
/
orderedmap.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
83
84
85
86
87
88
89
90
91
package common
import (
"reflect"
)
type OrderedMap struct {
m map[interface{}]interface{}
l []interface{}
}
type ErrInvalidType struct {
msg string
}
func (e *ErrInvalidType) Error() string {
return e.msg
}
func NewOrderedMap(m ...interface{}) *OrderedMap {
o := OrderedMap{make(map[interface{}]interface{}), make([]interface{}, 0)}
if len(m) > 0 {
o.SetMap(m[0])
}
return &o
}
func (o *OrderedMap) Clear() *OrderedMap {
o.m = make(map[interface{}]interface{})
o.l = make([]interface{}, 0)
return o
}
func (o *OrderedMap) SetMap(m ...interface{}) *OrderedMap {
o.Clear()
if len(m) > 1 || reflect.TypeOf(m[0]).Kind() != reflect.Map {
panic(&ErrInvalidType{"not a valid map type provided"})
}
if len(m) == 1 {
v := reflect.ValueOf(m[0])
for _, key := range v.MapKeys() {
value := v.MapIndex(key)
o.Set(key.Interface(), value.Interface())
}
}
return o
}
func (o *OrderedMap) Set(key interface{}, value interface{}) *OrderedMap {
delete(o.m, key)
o.m[key] = value
o.l = append(o.l, key)
return o
}
func (o *OrderedMap) Get(key interface{}) (interface{}, bool) {
value, ok := o.m[key]
return value, ok
}
func (o *OrderedMap) Delete(key interface{}) *OrderedMap {
delete(o.m, key)
for i, k := range o.l {
if key == k {
o.l = append(o.l[:i], o.l[i+1:]...)
break
}
}
return o
}
func (o *OrderedMap) Len() int {
return len(o.m)
}
func (o *OrderedMap) Keys() []interface{} {
return o.l
}