-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathset.go
More file actions
76 lines (68 loc) · 2.18 KB
/
set.go
File metadata and controls
76 lines (68 loc) · 2.18 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
package examples
// Borrowed from https://www.bytesizego.com/blog/set-in-golang
// Set is a collection of unique elements.
//
// Contract:
// - invariant Set.elements != nil
type Set struct {
elements map[string]struct{}
}
// NewSet creates a new set.
//
// Contract:
// - ensures s.elements != nil && len(s.elements) == 0
func NewSet() (s *Set) {
return &Set{
elements: map[string]struct{}{},
}
}
// Add inserts an element into the set.
//
// Contract:
// - ensures element is present in the set: s.Contains(value)
// - let alreadyPresent := s.Contains(value)
// - ensures cardinality grows if new element: !alreadyPresent ==> @old{len(s.elements)} == len(s.elements) - 1
// - ensures cardinality remains the same if no new element: alreadyPresent ==> @old{len(s.elements)} == len(s.elements)
func (s *Set) Add(value string) {
s.elements[value] = struct{}{}
}
// Remove deletes an element from the set.
//
// Contract:
// - ensures element is not present in the set: !s.Contains(value)
// - let alreadyPresent := s.Contains(value)
// - ensures cardinality shirks if element was in the set: alreadyPresent ==> @old{len(s.elements)-1} == len(s.elements)
// - ensures cardinality remains the same if element was not in the set: !alreadyPresent ==> @old{len(s.elements)} == len(s.elements)
func (s *Set) Remove(value string) {
delete(s.elements, value)
}
// Contains checks if an element is in the set.
//
// Contract:
// - ensures _, ok := s.elements[value]; ok ==> result == true
// - ensures _, ok := s.elements[value]; !ok ==> result != true
// - unmodified len(s.elements)
func (s *Set) Contains(value string) (result bool) {
_, found := s.elements[value]
return found
}
// Size returns the number of elements in the set.
//
// Contract:
// - ensures result == @old{len(s.elements)}
// - unmodified len(s.elements)
func (s *Set) Size() (result int) {
return len(s.elements)
}
// List returns all elements in the set as a slice.
//
// Contract:
// - ensures len(result) == len(s.elements)
// - unmodified len(s.elements)
func (s *Set) List() (result []string) {
keys := make([]string, 0, len(s.elements))
for key := range s.elements {
keys = append(keys, key)
}
return keys
}