-
Notifications
You must be signed in to change notification settings - Fork 0
/
ordered_map.go
123 lines (101 loc) · 1.83 KB
/
ordered_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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package orderedmap
type OrderedMap[K comparable, V any] []Pair[K, V]
type Pair[K comparable, V any] struct {
Key K
Val V
}
func (p Pair[K, V]) Equal(other Pair[K, V]) bool {
return p.Key == other.Key && any(p.Val) == any(other.Val)
}
func New[K comparable, V any]() OrderedMap[K, V] {
return OrderedMap[K, V]{}
}
func (m OrderedMap[K, V]) Has(key K) bool {
_, ok := m.Get(key)
return ok
}
func (m OrderedMap[K, V]) Get(key K) (V, bool) {
for _, p := range m {
if p.Key == key {
return p.Val, true
}
}
var zero V
return zero, false
}
func (m *OrderedMap[K, V]) Set(key K, val V) {
if m == nil {
*m = OrderedMap[K, V]{}
}
for i, p := range *m {
if p.Key == key {
(*m)[i].Val = val
return
}
}
*m = append(*m, Pair[K, V]{key, val})
}
func (m *OrderedMap[K, V]) Delete(key K) {
if m == nil || len(*m) == 0 {
return
}
for i, p := range *m {
if p.Key == key {
*m = append((*m)[:i], (*m)[i+1:]...)
return
}
}
}
func (m OrderedMap[K, V]) Keys() []K {
if m == nil {
return nil
}
keys := make([]K, len(m))
for i, p := range m {
keys[i] = p.Key
}
return keys
}
func (m OrderedMap[K, V]) Values() []V {
if m == nil {
return nil
}
values := make([]V, len(m))
for i, p := range m {
values[i] = p.Val
}
return values
}
func (m *OrderedMap[K, V]) Clear() {
if m == nil || len(*m) == 0 {
return
}
*m = []Pair[K, V]{}
}
func (m OrderedMap[K, V]) Clone() OrderedMap[K, V] {
if m == nil {
return nil
}
return append([]Pair[K, V]{}, m...)
}
func (m OrderedMap[K, V]) Equal(other OrderedMap[K, V]) bool {
if len(m) != len(other) {
return false
}
for i, p := range m {
if !p.Equal(other[i]) {
return false
}
}
return true
}
func (m OrderedMap[K, V]) DeepCopyInto(out *OrderedMap[K, V]) {
if out == nil {
return
}
if m == nil {
*out = nil
return
}
*out = m.Clone()
}