This repository has been archived by the owner on Apr 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
set.go
143 lines (129 loc) · 2.52 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package c3
type set struct {
version int
items map[interface{}]bool
}
func (s *set) Add(item interface{}) bool {
if s.Contains(item) {
return false
}
s.items[item] = true
s.version++
return true
}
func (s *set) Contains(item interface{}) bool {
return s.items[item]
}
func (s *set) Delete(item interface{}) bool {
if s.Contains(item) {
delete(s.items, item)
s.version++
return true
}
return false
}
func (s *set) Clear() {
if s.Len() == 0 {
return
}
s.items = make(map[interface{}]bool)
s.version++
}
func (s *set) Len() int {
return len(s.items)
}
func (s *set) Iterator() Iterator {
// TODO optimize this, it's horrible...
return MakeIterable(func() Generate {
var items = make([]interface{}, 0, s.Len())
for k, _ := range s.items {
items = append(items, k)
}
iter := items[:]
version := s.version
return func() (interface{}, bool) {
if s.version != version {
panic("Concurrent modification detected")
}
if len(iter) == 0 {
return defaultElementValue, false
}
item := iter[0]
iter = iter[1:]
return item, true
}
}).Iterator()
}
func (s *set) Intersection(other Set) Set {
result := NewSet()
os, ok := other.(*set)
if ok {
// fast path
for item, _ := range os.items {
if s.Contains(item) {
result.Add(item)
}
}
} else {
// slow path
for i := other.Iterator(); i.MoveNext(); {
if s.Contains(i.Value()) {
result.Add(i.Value())
}
}
}
return result
}
func (s *set) Difference(other Set) Set {
result := NewSet()
for item, _ := range s.items {
if !other.Contains(item) {
result.Add(item)
}
}
return result
}
func (s *set) Union(other Set) Set {
result := NewSet()
for item, _ := range s.items {
result.Add(item)
}
os, ok := other.(*set)
if ok {
// fast path
for item, _ := range os.items {
result.Add(item)
}
} else {
// slow path
for i := other.Iterator(); i.MoveNext(); {
result.Add(i.Value())
}
}
return result
}
func (s *set) SymmetricDifference(other Set) Set {
result := NewSet()
for item, _ := range s.items {
if !other.Contains(item) {
result.Add(item)
}
}
os, ok := other.(*set)
if ok {
// fast path
for item, _ := range os.items {
if !s.Contains(item) {
result.Add(item)
}
}
} else {
// slow path
for i := other.Iterator(); i.MoveNext(); {
if !s.Contains(i.Value()) {
result.Add(i.Value())
}
}
}
return result
}