/
numeric.go
113 lines (103 loc) · 1.98 KB
/
numeric.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package templates
import (
"math"
"strconv"
"text/template"
"github.com/loov/goda/internal/memory"
)
func numericFuncs() template.FuncMap {
return template.FuncMap{
"add": add,
"div": div,
"sub": sub,
"mul": mul,
"float": toFloat64,
"int": func(v interface{}) int64 { return int64(toFloat64(v)) },
"round": func(v interface{}) float64 { return math.Round(toFloat64(v)) },
"log": func(v interface{}) float64 { return math.Log(toFloat64(v)) },
"log10": func(v interface{}) float64 { return math.Log10(toFloat64(v)) },
"log2": func(v interface{}) float64 { return math.Log2(toFloat64(v)) },
}
}
func add(xs ...interface{}) float64 {
if len(xs) == 0 {
return math.NaN()
}
total := toFloat64(xs[0])
for _, x := range xs[1:] {
total += toFloat64(x)
}
return total
}
func div(xs ...interface{}) float64 {
if len(xs) == 0 {
return math.NaN()
}
total := toFloat64(xs[0])
for _, x := range xs[1:] {
total /= toFloat64(x)
}
return total
}
func sub(xs ...interface{}) float64 {
if len(xs) == 0 {
return math.NaN()
}
total := toFloat64(xs[0])
for _, x := range xs[1:] {
total -= toFloat64(x)
}
return total
}
func mul(xs ...interface{}) float64 {
if len(xs) == 0 {
return math.NaN()
}
total := toFloat64(xs[0])
for _, x := range xs[1:] {
total *= toFloat64(x)
}
return total
}
func toFloat64(v interface{}) float64 {
switch v := v.(type) {
case float64:
return v
case float32:
return float64(v)
case int:
return float64(v)
case int64:
return float64(v)
case int32:
return float64(v)
case int16:
return float64(v)
case int8:
return float64(v)
case uint:
return float64(v)
case uint64:
return float64(v)
case uint32:
return float64(v)
case uint16:
return float64(v)
case uint8:
return float64(v)
case memory.Bytes:
return float64(v)
case string:
if x, err := strconv.ParseFloat(v, 64); err == nil {
return x
}
return math.NaN()
case bool:
if v {
return 1
}
return 0
default:
return math.NaN()
}
}