-
Notifications
You must be signed in to change notification settings - Fork 10
/
set.go
96 lines (82 loc) · 1.96 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
package graphs
// A Set is a container that contains each element just once.
type Set[T comparable] map[T]struct{}
// NewSet creates a new empty set.
func NewSet[T comparable]() *Set[T] {
return &Set[T]{}
}
// NewSetWithElements creates a new set with the given
// arguments as elements.
func NewSetWithElements[T comparable](elements ...T) *Set[T] {
set := NewSet[T]()
for _, element := range elements {
set.Add(element)
}
return set
}
// Add adds an element to the set. It returns true if the
// element has been added and false if the set already contained
// that element.
func (s *Set[T]) Add(element T) bool {
_, exists := (*s)[element]
(*s)[element] = struct{}{}
return !exists
}
// Len returns the number of elements.
func (s *Set[T]) Len() int {
return len(*s)
}
// Equals returns whether the given set is equal to the receiver.
func (s *Set[T]) Equals(s2 *Set[T]) bool {
if s2 == nil || s.Len() != s2.Len() {
return false
}
for element, _ := range *s {
if !s2.Contains(element) {
return false
}
}
return true
}
// Contains returns whether the set contains the given element.
func (s *Set[T]) Contains(element T) bool {
_, exists := (*s)[element]
return exists
}
// Merge adds the elements of the given set to the receiver.
func (s *Set[T]) Merge(s2 *Set[T]) {
if s2 == nil {
return
}
for element, _ := range *s2 {
s.Add(element)
}
}
// Remove removes the given element from the set and returns
// whether the element was removed from the set.
func (s *Set[T]) Remove(element T) bool {
if _, exists := (*s)[element]; exists {
delete(*s, element)
return true
}
return false
}
// Any returns any element from the set.
func (s *Set[T]) Any() T {
for v, _ := range *s {
return v
}
panic("graphs: empty set")
}
// Each executes the given function for each element
// in the set.
func (s *Set[T]) Each(f func(T, func())) {
stopped := false
stop := func() { stopped = true }
for v, _ := range *s {
f(v, stop)
if stopped {
return
}
}
}