-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathset.go
More file actions
106 lines (91 loc) · 1.79 KB
/
set.go
File metadata and controls
106 lines (91 loc) · 1.79 KB
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
package blocktree
// Set is a set data structure
type Set[T comparable] struct {
items map[T]bool
}
// NewSet creates a new set with the given entries
func NewSet[T comparable](entries ...T) *Set[T] {
items := make(map[T]bool)
for _, item := range entries {
items[item] = true
}
return &Set[T]{
items: items,
}
}
// Remove removes an item from the set
func (s Set[T]) Remove(item T) {
delete(s.items, item)
}
// Add adds an item to the set
func (s Set[T]) Add(item T) {
s.items[item] = true
}
func (s Set[T]) Extend(items []T) {
for _, item := range items {
s.Add(item)
}
}
// Contains returns true if the set contains the item
func (s Set[T]) Contains(item T) bool {
_, ok := s.items[item]
return ok
}
// Size returns the number of items in the set
func (s Set[T]) Size() int {
return len(s.items)
}
// ToSlice returns a slice of all items in the set
func (s Set[T]) ToSlice() []T {
var slice []T
for k := range s.items {
slice = append(slice, k)
}
return slice
}
func (s Set[T]) Union(other Set[T]) *Set[T] {
union := NewSet[T]()
for k := range s.items {
union.Add(k)
}
for k := range other.items {
union.Add(k)
}
return union
}
func (s Set[T]) Intersect(other Set[T]) *Set[T] {
intersection := NewSet[T]()
for k := range s.items {
if other.Contains(k) {
intersection.Add(k)
}
}
return intersection
}
func (s Set[T]) Difference(other *Set[T]) *Set[T] {
difference := NewSet[T]()
for k := range s.items {
if !other.Contains(k) {
difference.Add(k)
}
}
return difference
}
func (s Set[T]) ForEach(cb func(T) bool) {
for k := range s.items {
if !cb(k) {
break
}
}
}
func (s Set[T]) Equals(other *Set[T]) bool {
if s.Size() != other.Size() {
return false
}
for k := range s.items {
if !other.Contains(k) {
return false
}
}
return true
}