-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathordered_map.go
96 lines (80 loc) · 1.65 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
package ordered
import "cmp"
type Key interface {
comparable
cmp.Ordered
}
type OrderedMap[K Key, V any] struct {
keys []K
values map[K]V
}
func NewMap[K Key, V any]() *OrderedMap[K, V] {
return &OrderedMap[K, V]{
keys: make([]K, 0),
values: make(map[K]V),
}
}
func (m *OrderedMap[K, V]) Set(key K, value V) {
if _, ok := m.values[key]; !ok {
m.keys = append(m.keys, key)
}
m.values[key] = value
}
func (m *OrderedMap[K, V]) Get(key K) (V, bool) {
value, ok := m.values[key]
return value, ok
}
func (m *OrderedMap[K, V]) Has(key K) bool {
_, ok := m.values[key]
return ok
}
func (m *OrderedMap[K, V]) Del(key K) {
delete(m.values, key)
for i, k := range m.keys {
if k == key {
m.keys = append(m.keys[:i], m.keys[i+1:]...)
break
}
}
}
func (m *OrderedMap[K, V]) Keys() []K {
return m.keys
}
func (m *OrderedMap[K, V]) Values() []V {
values := make([]V, len(m.keys))
for i, key := range m.keys {
values[i] = m.values[key]
}
return values
}
func (m *OrderedMap[K, V]) Len() int {
return len(m.keys)
}
func (m *OrderedMap[K, V]) Clear() {
m.keys = make([]K, 0)
m.values = make(map[K]V)
}
func (m *OrderedMap[K, V]) Clone() *OrderedMap[K, V] {
clone := NewMap[K, V]()
for _, key := range m.keys {
clone.Set(key, m.values[key])
}
return clone
}
func (m *OrderedMap[K, V]) Merge(other *OrderedMap[K, V]) {
for _, key := range other.keys {
m.Set(key, other.values[key])
}
}
func (m *OrderedMap[K, V]) MergeMap(other map[K]V) {
for key, value := range other {
m.Set(key, value)
}
}
func (m *OrderedMap[K, V]) Range(f func(key K, value V) bool) {
for _, key := range m.keys {
if !f(key, m.values[key]) {
break
}
}
}