-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
116 lines (100 loc) · 2.01 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
113
114
115
116
//+build with_deprecated
package mob
import "encoding/json"
type (
Set interface {
Len() int
Add(v interface{}) bool
Contains(v interface{}) bool
Remove(v interface{})
Collection() []interface{}
Foreach(cb func(interface{}))
Intersection(other Set) Set
Subtraction(other Set) Set
Clone() Set
}
setImpl struct {
holder map[interface{}]uint8
}
)
func NewSet() Set {
return NewSetWithCap(16)
}
func NewSetWithCap(capHint int) Set {
return &setImpl{
holder: make(map[interface{}]uint8, capHint),
}
}
func NewSetFromStrings(arr []string) Set {
out := NewSetWithCap(len(arr))
for _, it := range arr {
out.Add(it)
}
return out
}
func (this *setImpl) Len() int {
return len(this.holder)
}
func (this *setImpl) Add(v interface{}) (ok bool) {
if this.Contains(v) {
return false
}
this.holder[v] = 0
return true
}
func (this *setImpl) Contains(v interface{}) bool {
_, ok := this.holder[v]
return ok
}
func (this *setImpl) Remove(v interface{}) {
delete(this.holder, v)
}
func (this *setImpl) Collection() []interface{} {
out := make([]interface{}, 0, len(this.holder))
this.Foreach(func(it interface{}) {
out = append(out, it)
})
return out
}
func (this *setImpl) Foreach(cb func(interface{})) {
if cb == nil {
return
}
for k := range this.holder {
cb(k)
}
}
func (this *setImpl) Intersection(other Set) Set {
var smaller Set = this
if this.Len() > other.Len() {
smaller, other = other, this
}
outSet := NewSetWithCap(smaller.Len())
smaller.Foreach(func(i interface{}) {
if other.Contains(i) {
outSet.Add(i)
}
})
return outSet
}
func (this *setImpl) Subtraction(other Set) Set {
in := this.Intersection(other)
out := NewSet()
this.Foreach(func(i interface{}) {
if !in.Contains(i) {
out.Add(i)
}
})
other.Foreach(func(i interface{}) {
if !in.Contains(i) {
out.Add(i)
}
})
return out
}
func (this *setImpl) Clone() Set {
thisByte, _ := json.Marshal(this.holder)
outSet := NewSet().(*setImpl)
_ = json.Unmarshal(thisByte, &outSet.holder)
return outSet
}