-
Notifications
You must be signed in to change notification settings - Fork 0
/
other.go
91 lines (82 loc) · 1.47 KB
/
other.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
package just
import (
"context"
"time"
)
// Bool returns true if the element is not equal to the default value
// for this type.
func Bool[T builtin](v T) bool {
switch x := any(v).(type) {
case bool:
return x
case uint8:
return x > zero
case uint16:
return x > zero
case uint32:
return x > zero
case uint64:
return x > zero
case int8:
return x > zero
case int16:
return x > zero
case int32:
return x > zero
case int64:
return x > zero
case float32:
return x > zero
case float64:
return x > zero
case int:
return x > zero
case uint:
return x > zero
case uintptr:
return x > zero
case string:
return x != ""
}
return false
}
// Must will panic on an error after calling typical function.
func Must[T any](val T, err error) T {
if err != nil {
panic(err)
}
return val
}
func RunAfter(ctx context.Context, ticker <-chan time.Time, runNow bool, fn func(ctx context.Context) error) error {
if runNow {
if err := fn(ctx); err != nil {
return err
}
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker:
if err := fn(ctx); err != nil {
return err
}
}
}
}
// If return val1 when condition is true; val2 in other case.
//
// Usable to simplify constructions like:
//
// var username string
// if request.Username != "" {
// username = request.Username
// } else {
// username = "__unknown__"
// }
func If[T any](condition bool, val1, val2 T) T {
if condition {
return val1
}
return val2
}