-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
140 lines (111 loc) · 2.47 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
* Author: fasion
* Created time: 2022-11-19 18:46:55
* Last Modified by: fasion
* Last Modified time: 2024-05-09 14:13:20
*/
package stl
type Set[Data comparable] map[Data]struct{}
func NewSet[Data comparable](datas ...Data) Set[Data] {
return NewEmptySet[Data]().PushX(datas...)
}
func NewEmptySet[Data comparable]() Set[Data] {
return Set[Data]{}
}
func (set Set[Data]) Contain(data Data) bool {
_, ok := set[data]
return ok
}
func (set Set[Data]) ContainAll(datas ...Data) bool {
return AllMatch(datas, set.Contain)
}
func (set Set[Data]) ContainAny(datas ...Data) bool {
return AnyMatch(datas, set.Contain)
}
func (set Set[Data]) Len() int {
return len(set)
}
func (set Set[Data]) Empty() bool {
return set.Len() == 0
}
func (set Set[Data]) Equal(other Set[Data]) bool {
if set.Len() != other.Len() {
return false
}
for data := range set {
if !other.Contain(data) {
return false
}
}
return true
}
func (set Set[Data]) Slice() Slice[Data] {
return MapKeys(set)
}
func (set Set[Data]) Dup() Set[Data] {
return DupMap(set)
}
func (set Set[Data]) Push(data Data) Set[Data] {
set[data] = struct{}{}
return set
}
func (set Set[Data]) PushX(datas ...Data) Set[Data] {
for _, data := range datas {
set.Push(data)
}
return set
}
func (set Set[Data]) Pop(data Data) Set[Data] {
delete(set, data)
return set
}
func (set Set[Data]) Add(data Data) Set[Data] {
return set.Push(data)
}
func (set Set[Data]) AddX(datas ...Data) Set[Data] {
return set.PushX(datas...)
}
func (set Set[Data]) Merge(other Set[Data]) Set[Data] {
return ConcatMapInplace(set, other)
}
func (set Set[Data]) Purge(other Set[Data]) Set[Data] {
return BatchDeleteMapFromAnother(set, other)
}
func (set Set[Data]) Union(other Set[Data]) Set[Data] {
return ConcatMap(set, other)
}
func (set Set[Data]) Difference(other Set[Data]) Set[Data] {
return set.Dup().Purge(other)
}
func (set Set[Data]) SymmetricDifference(other Set[Data]) Set[Data] {
result := Set[Data]{}
for data := range set {
if !other.Contain(data) {
result.Push(data)
}
}
for data := range other {
if !set.Contain(data) {
result.Push(data)
}
}
return result
}
func (set Set[Data]) Intersection(other Set[Data]) Set[Data] {
result := Set[Data]{}
for data := range set {
if other.Contain(data) {
result.Push(data)
}
}
return result
}
func (set Set[Data]) FirstAppear(datas ...Data) (result Data) {
for _, data := range datas {
if set.Contain(data) {
result = data
return
}
}
return
}