-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.go
90 lines (72 loc) · 1.51 KB
/
math.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
package just
// Max returns the max number from `in`.
func Max[T number](in ...T) T {
if len(in) == 0 {
panic("cannot find max of nothing")
}
if len(in) == 1 {
return in[0]
}
res := in[0]
for i := 1; i < len(in); i++ {
if in[i] > res {
res = in[i]
}
}
return res
}
// MaxOr returns the max element from `in` or defaultVal when `in` is empty.
func MaxOr[T number](defaultVal T, in ...T) T {
if len(in) == 0 {
return defaultVal
}
return Max(in...)
}
// MaxDefault returns the max element from `in` or the default value for
// a specified type when `in` is empty.
func MaxDefault[T number](in ...T) T {
return MaxOr(0, in...)
}
// Min returns the min number from `in`.
func Min[T number](in ...T) T {
if len(in) == 0 {
panic("cannot find min of nothing")
}
if len(in) == 1 {
return in[0]
}
res := in[0]
for i := 1; i < len(in); i++ {
if in[i] < res {
res = in[i]
}
}
return res
}
// MinOr returns the min element from `in` or defaultVal when `in` is empty.
func MinOr[T number](defaultVal T, in ...T) T {
if len(in) == 0 {
return defaultVal
}
return Min(in...)
}
// MinDefault returns the min element from `in` or the default value for
// a specified type when `in` is empty.
func MinDefault[T number](in ...T) T {
return MinOr(0, in...)
}
// Sum returns the sum of numbers from `in`.
func Sum[T number](in ...T) T {
var acc T
for i := range in {
acc += in[i]
}
return acc
}
// Abs returns the abs value of v.
func Abs[T number](v T) T {
if v < 0 {
return -v
}
return v
}