-
Notifications
You must be signed in to change notification settings - Fork 1
/
set.go
62 lines (47 loc) · 988 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
57
58
59
60
61
62
package ankabuffer
// based on string only https://gist.github.com/bgadrian/cb8b9344d9c66571ef331a14eb7a2e80
// rewritten to be generic
type Set[T comparable] struct {
list map[T]struct{} //empty structs occupy 0 memory
}
func (s *Set[T]) Has(v T) bool {
_, ok := s.list[v]
return ok
}
func (s *Set[T]) Add(v T) {
s.list[v] = struct{}{}
}
func (s *Set[T]) Remove(v T) {
delete(s.list, v)
}
func (s *Set[T]) Clear() {
s.list = make(map[T]struct{})
}
func (s *Set[T]) Size() int {
return len(s.list)
}
func NewSet[T comparable]() *Set[T] {
s := &Set[T]{}
s.list = make(map[T]struct{})
return s
}
func (s *Set[T]) Slice() []T {
var res = make([]T, 0, len(s.list))
for k := range s.list {
res = append(res, k)
}
return res
}
func (s *Set[T]) AddMulti(list ...T) {
for _, v := range list {
s.Add(v)
}
}
// fp
func Map[T, U any](data []T, f func(T) U) []U {
res := make([]U, 0, len(data))
for _, e := range data {
res = append(res, f(e))
}
return res
}