-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
106 lines (89 loc) · 1.53 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
package set
import (
"fmt"
"reflect"
"strings"
)
type Set[T comparable] map[T]struct{}
func New[T comparable](v ...T) Set[T] {
set := make(Set[T], len(v))
set.AddAll(v...)
return set
}
func (s Set[T]) Has(v T) bool {
_, ok := s[v]
return ok
}
func (s Set[T]) HasAll(vals ...T) bool {
for _, v := range vals {
if !s.Has(v) {
return false
}
}
return true
}
func (s Set[T]) HasAny(vals ...T) bool {
for _, v := range vals {
if s.Has(v) {
return true
}
}
return false
}
func (s Set[T]) Add(v T) {
s[v] = struct{}{}
}
func (s Set[T]) AddAll(vals ...T) {
for _, v := range vals {
s[v] = struct{}{}
}
}
func (s Set[T]) Remove(v T) {
delete(s, v)
}
func (s Set[T]) Values() []T {
t := make([]T, 0, len(s))
for v := range s {
t = append(t, v)
}
return t
}
func (s Set[T]) GoString() string {
var buf strings.Builder
buf.WriteString(`set.New[`)
buf.WriteString(reflect.TypeOf(*new(T)).String())
buf.WriteString(`](`)
first := true
for v := range s {
if !first {
buf.WriteString(`, `)
}
first = false
buf.WriteString(fmt.Sprintf(`%#v`, v))
}
buf.WriteString(`)`)
return buf.String()
}
func Intersect[T comparable](a, b Set[T]) Set[T] {
lenA, lenB := len(a), len(b)
if lenA > lenB {
lenA = lenB
}
out := make(Set[T], lenA)
for v := range a {
if _, ok := b[v]; ok {
out[v] = struct{}{}
}
}
return out
}
func Union[T comparable](a, b Set[T]) Set[T] {
out := make(Set[T], len(a)+len(b))
for v := range a {
out[v] = struct{}{}
}
for v := range b {
out[v] = struct{}{}
}
return out
}