| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
package linkedhashmap |
| 13 |
|
| 14 |
import ( |
| 15 |
"fmt" |
| 16 |
"strings" |
| 17 |
|
| 18 |
"github.com/emirpasic/gods/v2/lists/doublylinkedlist" |
| 19 |
"github.com/emirpasic/gods/v2/maps" |
| 20 |
) |
| 21 |
|
| 22 |
|
| 23 |
var _ maps.Map[string, int] = (*Map[string, int])(nil) |
| 24 |
|
| 25 |
|
| 26 |
type Map[K comparable, V any] struct { |
| 27 |
table map[K]V |
| 28 |
ordering *doublylinkedlist.List[K] |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
func New[K comparable, V any]() *Map[K, V] { |
| 33 |
return &Map[K, V]{ |
| 34 |
table: make(map[K]V), |
| 35 |
ordering: doublylinkedlist.New[K](), |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
func (m *Map[K, V]) Put(key K, value V) { |
| 42 |
if _, contains := m.table[key]; !contains { |
| 43 |
m.ordering.Append(key) |
| 44 |
} |
| 45 |
m.table[key] = value |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
func (m *Map[K, V]) Get(key K) (value V, found bool) { |
| 52 |
value, found = m.table[key] |
| 53 |
return value, found |
| 54 |
} |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
func (m *Map[K, V]) Remove(key K) { |
| 59 |
if _, contains := m.table[key]; contains { |
| 60 |
delete(m.table, key) |
| 61 |
index := m.ordering.IndexOf(key) |
| 62 |
m.ordering.Remove(index) |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
func (m *Map[K, V]) Empty() bool { |
| 68 |
return m.Size() == 0 |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
func (m *Map[K, V]) Size() int { |
| 73 |
return m.ordering.Size() |
| 74 |
} |
| 75 |
|
| 76 |
|
| 77 |
func (m *Map[K, V]) Keys() []K { |
| 78 |
return m.ordering.Values() |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
func (m *Map[K, V]) Values() []V { |
| 83 |
values := make([]V, m.Size()) |
| 84 |
count := 0 |
| 85 |
it := m.Iterator() |
| 86 |
for it.Next() { |
| 87 |
values[count] = it.Value() |
| 88 |
count++ |
| 89 |
} |
| 90 |
return values |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
func (m *Map[K, V]) Clear() { |
| 95 |
clear(m.table) |
| 96 |
m.ordering.Clear() |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
func (m *Map[K, V]) String() string { |
| 101 |
str := "LinkedHashMap\nmap[" |
| 102 |
it := m.Iterator() |
| 103 |
for it.Next() { |
| 104 |
str += fmt.Sprintf("%v:%v ", it.Key(), it.Value()) |
| 105 |
} |
| 106 |
return strings.TrimRight(str, " ") + "]" |
| 107 |
|
| 108 |
} |