-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringSet.go
86 lines (68 loc) · 1.69 KB
/
StringSet.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
package utils
// StringSet represents a set of strings
type StringSet struct {
Set map[string]bool
}
func StringSetIntersection(sets ...StringSet) StringSet {
if len(sets) == 0{
return NewStringSet()
}
if len(sets) == 1 {
return sets[0]
}
return sets[0].Intersect(sets[1:]...)
}
// NewStringSet returns a newly created string set
func NewStringSet(elems ...string) StringSet {
res := StringSet{Set: make(map[string]bool)}
for _, elem := range elems {
res.Set[elem] = true
}
return res
}
// Add adds an element to the string set
func (s StringSet) Add(element string) {
s.Set[element] = true
}
// Remove removes an element from the string set
func (s StringSet) Remove(element string) {
if s.Has(element) {
delete(s.Set, element)
}
}
// Has checks if an element exists on the string set
func (s StringSet) Has(element string) bool {
_, ok := s.Set[element]
return ok
}
// Elements returns the elements of this set as a slice of strings
func (s StringSet) Elements() []string {
var res []string
for k := range s.Set {
res = append(res, k)
}
return res
}
// Intersect returns the intersection of a set with other sets
func (s StringSet) Intersect(otherSets ...StringSet) StringSet {
var res = NewStringSet(s.Elements()...)
for _, otherSet := range otherSets {
for k := range res.Set {
if !otherSet.Has(k) {
res.Remove(k)
}
}
}
return res
}
// Union merges a set with other sets, so the resulting values in the set
// wil be the values present in all sets
func (s StringSet) Union(otherSets ...StringSet) StringSet {
var res = NewStringSet(s.Elements()...)
for _, otherSet := range otherSets {
for elem := range otherSet.Set {
s.Add(elem)
}
}
return res
}