-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_set.go
84 lines (72 loc) · 1.25 KB
/
string_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
package set
var exists = struct{}{}
type stringSet struct {
v []string
m map[string]struct{}
}
func NewStringSet() *stringSet {
s := &stringSet{}
s.m = make(map[string]struct{})
s.v = []string{}
return s
}
func (s *stringSet) Add(value string) {
if s.Contains(value) {
return
}
s.m[value] = exists
s.v = append(s.v, value)
}
func (s *stringSet) AddValues(values []string) {
for _, v := range values {
s.Add(v)
}
}
func (s *stringSet) Remove(value string) {
if !s.Contains(value) {
return
}
delete(s.m, value)
s.v = sliceWithout(s.v, value)
}
func sliceWithout(s []string, v string) []string {
idx := -1
for i, item := range s {
if item == v {
idx = i
break
}
}
if idx < 0 {
return s
}
return append(s[:idx], s[idx+1:]...)
}
func (s *stringSet) RemoveValues(values []string) {
for _, v := range values {
s.Remove(v)
}
}
func (s *stringSet) Contains(value string) bool {
_, c := s.m[value]
return c
}
func (s *stringSet) Len() int {
return len(s.m)
}
func (s *stringSet) ToSlice() []string {
return s.v
}
func (s1 *stringSet) Equal(s2 *stringSet) bool {
if s1.Len() != s2.Len() {
return false
}
isEqual := true
for _, v := range s1.v {
if !s2.Contains(v) {
isEqual = false
break
}
}
return isEqual
}