forked from micvbang/go-helpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.go
92 lines (73 loc) · 1.6 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
package helpy
// Code generated. DO NOT EDIT.
type Set[T comparable] map[T]struct{}
// Contains returns true if Set contains v.
func (s Set[T]) Contains(v T) bool {
_, exists := s[v]
return exists
}
// Intersect returns the intersection of two Sets.
func (s Set[T]) Intersect(s2 Set[T]) Set[T] {
short, long := s, s2
if len(s2) < len(s) {
short, long = s2, s
}
m := make(map[T]struct{}, len(short))
for k := range short {
if _, exists := long[k]; exists {
m[k] = struct{}{}
}
}
return m
}
// Union returns the union of two Sets.
func (s Set[T]) Union(s2 Set[T]) Set[T] {
m := make(map[T]struct{}, len(s) + len(s2))
for k := range s {
m[k] = struct{}{}
}
for k := range s2 {
m[k] = struct{}{}
}
return m
}
// Subtract returns a new Set containing all values from s that are not in
// s2.
func (s Set[T]) Subtract(s2 Set[T]) Set[T] {
output := Set[T]{}
for v1 := range s {
if _, ok := s2[v1]; !ok{
output[v1] = struct{}{}
}
}
return output
}
// Add adds v to its elements
func (s *Set[T]) Add(v T) {
(*s)[v] = struct{}{}
}
// Equal returns true if s and s2 are of equal length and all elements
// contained in one set are contained in the other.
func (s Set[T]) Equal(s2 Set[T]) bool {
if len(s) != len(s2) {
return false
}
for v := range s {
if _, ok := s2[v]; !ok {
return false
}
}
return true
}
// ToSet returns a lookup map for T.
func ToSet[T comparable](vs []T) Set[T] {
m := make(map[T]struct{})
for _, v := range vs {
m[v] = struct{}{}
}
return m
}
// MakeSet returns a lookup map for T
func MakeSet[T comparable](vs ...T) Set[T] {
return ToSet(vs)
}