-
Notifications
You must be signed in to change notification settings - Fork 1
/
strset.go
99 lines (79 loc) · 2.02 KB
/
strset.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
package soaap
import (
"fmt"
"strings"
)
//
// A string set is a map from a string to an empty interface.
//
// It's a bit silly that Go doesn't have a built-in set type. It's truly
// absurd that Go doesn't support the polymorphism that would let us implement
// such a type properly (i.e., not have to implement "intset", "strset", etc.).
//
type strset map[string]interface{}
// Put an element into the set, whether or not it's already there.
func (s *strset) Add(key string) {
(*s)[key] = true
}
// Create a by-value copy of this data structure.
func (s strset) Clone() strset {
clone := make(strset)
clone.Union(s)
return clone
}
// Does this set contain a given element?
func (s strset) Contains(key string) bool {
_, ok := s[key]
return ok
}
// Join all of the strings in this set together.
func (s strset) Join(join string) string {
return strings.Join(s.Values(), join)
}
// Remove a string from a set and report whether or not it was actually there.
func (s *strset) Remove(key string) bool {
_, ok := (*s)[key]
delete(*s, key)
return ok
}
// The number of elements in the set.
func (s *strset) Size() int {
return len(*s)
}
// Compute the intersection of two sets, generating a third set without
// modifying either of the input sets.
func (s strset) Intersection(other strset) strset {
result := make(strset)
for k := range s {
_, ok := other[k]
if ok {
result[k] = true
}
}
return result
}
// Transform each key in the set according to a fmt.Sprintf format.
func (s strset) TransformEach(format string) strset {
result := strset{}
for key := range s {
result.Add(fmt.Sprintf(format, key))
}
return result
}
// Compute the union of two sets, generating a third set without modifying
// either of the input sets.
func (s strset) Union(other strset) strset {
result := s
for k := range other {
result[k] = true
}
return result
}
// Extract all values contained in the set.
func (s strset) Values() []string {
keys := make([]string, 0)
for key := range s {
keys = append(keys, key)
}
return keys
}