-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
56 lines (47 loc) · 819 Bytes
/
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
package collection
type (
void struct{}
Set[T comparable] map[T]void
)
func NewSet[T comparable](values ...T) Set[T] {
return NewSetFn(values, func(v T) T { return v })
}
func NewSetFn[T comparable, Y any](values []Y, fn func(Y) T) Set[T] {
s := make(Set[T])
for _, v := range values {
s.Add(fn(v))
}
return s
}
func (s Set[T]) Add(t T) {
s[t] = void{}
}
func (s Set[T]) Has(t T) (ok bool) {
_, ok = s[t]
return
}
func (s Set[T]) Delete(t T) (ok bool) {
r := s.Has(t)
delete(s, t)
return r
}
func (s Set[T]) Size() int {
return len(s)
}
func (s Set[T]) Values() []T {
vals := make([]T, s.Size())
var i int
s.Range(func(t T) bool {
vals[i] = t
i++
return true
})
return vals
}
func (s Set[T]) Range(fn func(T) bool) {
for k := range s {
if !fn(k) {
return
}
}
}