-
Notifications
You must be signed in to change notification settings - Fork 77
/
map.go
118 lines (101 loc) · 2.31 KB
/
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
package multimap
import (
g "github.com/zyedidia/generic"
"github.com/zyedidia/generic/avl"
)
type mapMultiMap[K comparable, V any, C valuesContainer[V]] struct {
baseMultiMap
keys map[K]C
makeValues func() C
}
func (m *mapMultiMap[K, V, C]) Dimension() int {
return len(m.keys)
}
func (m *mapMultiMap[K, V, C]) Count(key K) int {
values, ok := m.keys[key]
if !ok {
return 0
}
return values.Size()
}
func (m *mapMultiMap[K, V, C]) Has(key K) bool {
_, ok := m.keys[key]
return ok
}
func (m *mapMultiMap[K, V, C]) Get(key K) []V {
values, ok := m.keys[key]
if !ok {
return nil
}
return values.List()
}
func (m *mapMultiMap[K, V, C]) Put(key K, value V) {
values, ok := m.keys[key]
if !ok {
values = m.makeValues()
m.keys[key] = values
}
m.size += values.Put(value)
}
func (m *mapMultiMap[K, V, C]) Remove(key K, value V) {
values, ok := m.keys[key]
if !ok {
return
}
m.size -= values.Remove(value)
if values.Empty() {
delete(m.keys, key)
}
}
func (m *mapMultiMap[K, V, C]) RemoveAll(key K) {
values, ok := m.keys[key]
if !ok {
return
}
m.size -= values.Size()
delete(m.keys, key)
}
func (m *mapMultiMap[K, V, C]) Clear() {
m.size = 0
m.keys = map[K]C{}
}
func (m *mapMultiMap[K, V, C]) Each(fn func(key K, value V)) {
for key, values := range m.keys {
values.Each(func(value V) {
fn(key, value)
})
}
}
func (m *mapMultiMap[K, V, C]) EachAssociation(fn func(key K, values []V)) {
for key, values := range m.keys {
fn(key, values.List())
}
}
// NewMapSlice creates a MultiMap using builtin map and builtin slice.
// - Both key type and value type must be comparable.
// - Duplicate entries are permitted.
// - Both keys and values are unsorted.
func NewMapSlice[K, V comparable]() MultiMap[K, V] {
m := &mapMultiMap[K, V, *valuesSlice[V]]{
makeValues: func() *valuesSlice[V] {
return &valuesSlice[V]{}
},
}
m.Clear()
return m
}
// NewMapSet creates a MultiMap using builtin map and AVL set.
// - Key type must be comparable.
// - Duplicate entries are not permitted.
// - Values are sorted, but keys are unsorted.
func NewMapSet[K comparable, V any](valueLess g.LessFn[V]) MultiMap[K, V] {
m := &mapMultiMap[K, V, valuesSet[V]]{
makeValues: func() valuesSet[V] {
return valuesSet[V]{
t: avl.New[V, struct{}](valueLess),
}
},
}
m.Clear()
return m
}