-
Notifications
You must be signed in to change notification settings - Fork 1
/
orderedmap.go
82 lines (67 loc) · 1.67 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
package img2ansi
import (
"sync"
)
// OrderedMap represents an ordered map data structure
type OrderedMap struct {
keys []interface{}
values map[interface{}]interface{}
mu sync.RWMutex
}
// New creates a new OrderedMap
func NewOrderedMap() *OrderedMap {
return &OrderedMap{
keys: make([]interface{}, 0),
values: make(map[interface{}]interface{}),
}
}
// Set adds a Key-Value pair to the map
func (om *OrderedMap) Set(key, value interface{}) {
om.mu.Lock()
defer om.mu.Unlock()
if _, exists := om.values[key]; !exists {
om.keys = append(om.keys, key)
}
om.values[key] = value
}
// Get retrieves a Value from the map by Key
func (om *OrderedMap) Get(key interface{}) (interface{}, bool) {
om.mu.RLock()
defer om.mu.RUnlock()
val, exists := om.values[key]
return val, exists
}
// Delete removes a Key-Value pair from the map
func (om *OrderedMap) Delete(key interface{}) {
om.mu.Lock()
defer om.mu.Unlock()
if _, exists := om.values[key]; exists {
delete(om.values, key)
for i, k := range om.keys {
if k == key {
om.keys = append(om.keys[:i], om.keys[i+1:]...)
break
}
}
}
}
// Keys returns a slice of keys in the order they were inserted
func (om *OrderedMap) Keys() []interface{} {
om.mu.RLock()
defer om.mu.RUnlock()
return append([]interface{}{}, om.keys...)
}
// Iterate calls the provided function for each Key-Value pair in order
func (om *OrderedMap) Iterate(f func(key, value interface{})) {
om.mu.RLock()
defer om.mu.RUnlock()
for _, k := range om.keys {
f(k, om.values[k])
}
}
// Len returns the number of elements in the map
func (om *OrderedMap) Len() int {
om.mu.RLock()
defer om.mu.RUnlock()
return len(om.keys)
}