forked from diegoholiveira/jsonlogic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
75 lines (56 loc) · 1.2 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
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 {
return is(obj, reflect.Float64)
}
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 toNumber(value interface{}) float64 {
if isString(value) {
w, _ := strconv.ParseFloat(value.(string), 64)
return w
}
return value.(float64)
}
func toString(value interface{}) string {
if isNumber(value) {
return strconv.FormatFloat(value.(float64), 'f', -1, 64)
}
if value == nil {
return ""
}
return value.(string)
}