-
Notifications
You must be signed in to change notification settings - Fork 52
/
helpers.go
99 lines (79 loc) · 1.63 KB
/
helpers.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
package jsonlogic
import (
"reflect"
"strconv"
)
func is(obj interface{}, kind reflect.Kind) bool {
return obj != nil && reflect.TypeOf(obj).Kind() == kind
}
func isBool(obj interface{}) bool {
return is(obj, reflect.Bool)
}
func isString(obj interface{}) bool {
return is(obj, reflect.String)
}
func isNumber(obj interface{}) bool {
switch obj.(type) {
case int, float64:
return true
default:
return false
}
}
func isPrimitive(obj interface{}) bool {
return isBool(obj) || isString(obj) || isNumber(obj)
}
func isMap(obj interface{}) bool {
return is(obj, reflect.Map)
}
func isSlice(obj interface{}) bool {
return is(obj, reflect.Slice)
}
func isTrue(obj interface{}) bool {
if isBool(obj) {
return obj.(bool)
}
if isNumber(obj) {
n := toNumber(obj)
return n != 0
}
if isString(obj) || isSlice(obj) || isMap(obj) {
length := reflect.ValueOf(obj).Len()
return length > 0
}
return false
}
func toSliceOfNumbers(values interface{}) []float64 {
_values := values.([]interface{})
numbers := make([]float64, len(_values))
for i, n := range _values {
numbers[i] = toNumber(n)
}
return numbers
}
func toNumber(value interface{}) float64 {
if isString(value) {
w, _ := strconv.ParseFloat(value.(string), 64)
return w
}
switch value.(type) {
case int:
return float64(value.(int))
default:
return value.(float64)
}
}
func toString(value interface{}) string {
if isNumber(value) {
switch value.(type) {
case int:
return strconv.FormatInt(int64(value.(int)), 10)
default:
return strconv.FormatFloat(value.(float64), 'f', -1, 64)
}
}
if value == nil {
return ""
}
return value.(string)
}