-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_set.go
115 lines (95 loc) · 1.86 KB
/
utils_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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package dvonn
type Set struct {
list map[interface{}]struct{}
}
func GetSet() *Set {
return &Set{make(map[interface{}]struct{})}
}
func (s *Set) Has(v interface{}) bool {
_, ok := s.list[v]
return ok
}
func (s *Set) Add(v interface{}) {
s.list[v] = struct{}{}
}
func (s *Set) Remove(v interface{}) {
delete(s.list, v)
}
func (s *Set) Clear() {
s.list = make(map[interface{}]struct{})
}
func (s *Set) Size() int {
return len(s.list)
}
func NewSet() *Set {
s := &Set{}
s.list = make(map[interface{}]struct{})
return s
}
//optional functionalities
//AddMulti Add multiple values in the set
func (s *Set) AddMulti(list ...interface{}) {
for _, v := range list {
s.Add(v)
}
}
//AddMulti Add multiple values in the set
func (s *Set) AddMultiS(list []string) {
for _, v := range list {
s.Add(v)
}
}
type FilterFunc func(v interface{}) bool
// Filter returns a subset, that contains only the values that satisfies the given predicate P
func (s *Set) Filter(P FilterFunc) *Set {
res := NewSet()
for v := range s.list {
if P(v) == false {
continue
}
res.Add(v)
}
return res
}
func (s *Set) Union(s2 *Set) *Set {
res := NewSet()
for v := range s.list {
res.Add(v)
}
for v := range s2.list {
res.Add(v)
}
return res
}
func (s *Set) Intersect(s2 *Set) *Set {
res := NewSet()
for v := range s.list {
if s2.Has(v) == false {
continue
}
res.Add(v)
}
return res
}
// Difference returns the subset from s, that doesn't exists in s2 (param)
func (s *Set) Difference(s2 *Set) *Set {
res := NewSet()
for v := range s.list {
if s2.Has(v) {
continue
}
res.Add(v)
}
return res
}
func (s *Set) DifferenceS(s2 *Set) []string {
res := make([]string, 0)
for v := range s.list {
if s2.Has(v) {
continue
}
res = append(res, v.(string))
}
return res
}
// reference: https://gist.github.com/bgadrian/cb8b9344d9c66571ef331a14eb7a2e80