-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.go
97 lines (79 loc) · 1.78 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
package sets
// Set is a set of elements.
type Set[E comparable] map[E]struct{}
// New creates a new set with the given values.
func New[E comparable](values ...E) Set[E] {
s := Set[E]{}
for _, v := range values {
s[v] = struct{}{}
}
return s
}
// Add adds an element to the set.
func (s Set[E]) Add(v E) Set[E] {
s[v] = struct{}{}
return s
}
// Remove removes an element from the set.
func (s Set[E]) Remove(v E) Set[E] {
delete(s, v)
return s
}
// Contains checks if the set contains the given element.
func (s Set[E]) Contains(v E) bool {
_, ok := s[v]
return ok
}
// Items returns a slice of the items in the set.
func (s Set[E]) Items() []E {
result := make([]E, 0, len(s))
for v := range s {
result = append(result, v)
}
return result
}
// Intersection returns a new set with the intersection of the set and the given set.
func (s Set[E]) Intersection(s2 Set[E]) Set[E] {
result := New[E]()
for _, v := range s.Items() {
if s2.Contains(v) {
result.Add(v)
}
}
return result
}
// Diff returns a new set with the difference of the set and the given set.
func (s Set[E]) Diff(s2 Set[E]) Set[E] {
result := New[E]()
for _, v := range s.Items() {
if !s2.Contains(v) {
result.Add(v)
}
}
return result
}
// Intersects checks if the set intersects with the given set.
func (s Set[E]) Intersects(s2 Set[E]) bool {
for _, v := range s.Items() {
if s2.Contains(v) {
return true
}
}
return false
}
// Clone returns a new set with the same elements as the set.
func (s Set[E]) Clone() Set[E] {
result := New[E]()
for _, v := range s.Items() {
result.Add(v)
}
return result
}
// Count returns the number of elements in the set.
func (s Set[E]) Count() int {
return len(s)
}
// Flush removes all elements from the set.
func (s Set[E]) Flush() {
clear(s)
}