-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperators.go
68 lines (53 loc) · 1.32 KB
/
operators.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
package safe
import (
"math"
"golang.org/x/exp/constraints"
)
func Clamp[T Number](number, min, max T) T {
if number < min {
return min
} else if number > max {
return max
}
return number
}
func ClampMin[T Number](number, min T) T {
if number < min {
return min
}
return number
}
func ClampMax[T Number](number, max T) T {
if number > max {
return max
}
return number
}
// CompareFloats compares two floats. First, it tries to compare the floats exactly.
// Secondly, it compared them using the absolute tolerance if tolerance >= 0.
// Lastly, it compares the floats using the relative tolerance if relativeTolerance >= 0.
func CompareFloats[T constraints.Float](a, b, tolerance, relativeTolerance T) bool {
if a == b {
return true
}
if tolerance < 0 || relativeTolerance < 0 {
return false
}
diff := T(math.Abs(float64(a - b)))
if tolerance != 0 && diff <= Clamp(tolerance, 0, 1) {
return true
}
if relativeTolerance != 0 && diff <= max(a, b)*Clamp(relativeTolerance, 0, 1) {
return true
}
return false
}
// Ternary functions as a ternary ? operator found in functional programming.
// If the condition is true, it returns the first case, otherwise the secone case.
func Ternary[T any](condition bool, incase, otherwise T) T {
if condition {
return incase
} else {
return otherwise
}
}