-
Notifications
You must be signed in to change notification settings - Fork 21
/
set.go
103 lines (86 loc) · 1.5 KB
/
set.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
package types
import (
"cmp"
"github.com/jitsucom/bulker/jitsubase/utils"
"sort"
"strconv"
)
type Set[K cmp.Ordered] map[K]struct{}
func NewSet[K cmp.Ordered](values ...K) Set[K] {
s := make(Set[K])
s.PutAll(values)
return s
}
func (s Set[K]) Contains(key K) bool {
_, ok := s[key]
return ok
}
func (s Set[K]) Put(key K) {
s[key] = struct{}{}
}
func (s Set[K]) PutAll(keys []K) {
for _, key := range keys {
s.Put(key)
}
}
func (s Set[K]) PutAllOrderedKeys(m *OrderedMap[K, any]) {
for el := m.Front(); el != nil; el = el.Next() {
s.Put(el.Key)
}
}
func (s Set[K]) PutAllKeys(m map[K]any) {
for key := range m {
s.Put(key)
}
}
func (s Set[K]) PutSet(keys Set[K]) {
for key := range keys {
s.Put(key)
}
}
func (s Set[K]) Remove(key K) {
delete(s, key)
}
func (s Set[K]) Clear() {
for key := range s {
delete(s, key)
}
}
func (s Set[K]) Clone() Set[K] {
newSet := make(Set[K])
for k := range s {
newSet.Put(k)
}
return newSet
}
func (s Set[K]) Size() int {
return len(s)
}
func (s Set[K]) ToSlice() []K {
if len(s) == 0 {
return []K{}
}
slice := make([]K, 0, len(s))
for k := range s {
slice = append(slice, k)
}
sort.Slice(slice, func(i, j int) bool {
return slice[i] < slice[j]
})
return slice
}
func (s Set[K]) Equals(other Set[K]) bool {
if len(s) != len(other) {
return false
}
for k := range s {
if !other.Contains(k) {
return false
}
}
return true
}
func (s Set[K]) Hash() string {
h, _ := utils.HashAny(s)
return strconv.FormatUint(h, 10)
}