-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
85 lines (66 loc) · 1.26 KB
/
utils.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
package main
import (
"os"
"strings"
)
func TruncateText(s string, max int) string {
if max > len(s) {
return s
}
return s[:strings.LastIndex(s[:max], " ")] + " ..."
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func sliceContains[T comparable](s []T, str T) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
// 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 []T
for v := range s.list {
res = append(res, v)
}
return res
}
// 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
}