-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathset.go
58 lines (48 loc) · 1.14 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
// Package mapset provides an implementation of a set using the built-in map.
package mapset
import "golang.org/x/exp/maps"
// Set implements a hashset, using the hashmap as the underlying storage.
type Set[K comparable] struct {
m map[K]struct{}
}
// New returns an empty hashset.
func New[K comparable]() Set[K] {
return Set[K]{
m: make(map[K]struct{}),
}
}
// Of returns a new hashset initialized with the given 'vals'
func Of[K comparable](vals ...K) Set[K] {
s := New[K]()
for _, val := range vals {
s.Put(val)
}
return s
}
// Put adds 'val' to the set.
func (s Set[K]) Put(val K) {
s.m[val] = struct{}{}
}
// Has returns true only if 'val' is in the set.
func (s Set[K]) Has(val K) bool {
_, ok := s.m[val]
return ok
}
// Remove removes 'val' from the set.
func (s Set[K]) Remove(val K) {
delete(s.m, val)
}
// Clear removes all elements from the set.
func (s Set[K]) Clear() {
maps.Clear(s.m)
}
// Size returns the number of elements in the set.
func (s Set[K]) Size() int {
return len(s.m)
}
// Each calls 'fn' on every item in the set in no particular order.
func (s Set[K]) Each(fn func(key K)) {
for k := range s.m {
fn(k)
}
}