-
Notifications
You must be signed in to change notification settings - Fork 2
/
set.go
112 lines (94 loc) · 1.57 KB
/
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
package ctk
type Set struct {
cache map[interface{}]struct{}
}
func NewSet(s ...interface{}) *Set {
result := Set{cache: make(map[interface{}]struct{})}
if s != nil {
for _, v := range s {
result.Add(v)
}
}
return &result
}
func (s *Set) Add(val ...interface{}) {
if val == nil {
return
}
for _, v := range val {
s.cache[v] = struct{}{}
}
}
func (s *Set) Adds(set *Set) {
if set == nil {
return
}
for k := range set.cache {
s.cache[k] = struct{}{}
}
}
// 交集
func (s *Set) Intersect(set *Set) *Set {
if s == nil || set == nil {
return nil
}
result := NewSet()
for k := range s.cache {
if set.Contains(k) {
result.Add(k)
}
}
return result
}
// 差集
func (s *Set) Difference(set *Set) *Set {
return nil
}
// 并集
func (s *Set) Union(set *Set) *Set {
return nil
}
// 补集 余集
func (s *Set) Supplementary(set *Set) *Set {
if s == nil || set == nil {
return nil
}
for k := range set.cache {
s.Remove(k)
}
return s
}
func (s *Set) Len() int {
return len(s.cache)
}
func (s *Set) IsEmpty() bool {
return len(s.cache) == 0
}
func (s *Set) Contains(val interface{}) bool {
_, ok := s.cache[val]
return ok
}
func (s *Set) Remove(val interface{}) {
delete(s.cache, val)
}
func (s *Set) Clear() {
s.cache = make(map[interface{}]struct{})
}
func (s *Set) Loop(action func(interface{})) {
for k, _ := range s.cache {
action(k)
}
}
func (s *Set) Intersection(set *Set) *Set {
if set == nil {
return nil
}
result := NewSet()
for k := range s.cache {
_, ok := set.cache[k]
if ok {
result.Add(k)
}
}
return result
}