-
Notifications
You must be signed in to change notification settings - Fork 8
/
hit.go
123 lines (117 loc) · 2.51 KB
/
hit.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
114
115
116
117
118
119
120
121
122
123
package hit
import (
"fmt"
"reflect"
"runtime"
"strconv"
"time"
)
// callFn if args[i] == func, run it
func callFn(f interface{}) interface{} {
if f != nil {
t := reflect.TypeOf(f)
if t.Kind() == reflect.Func && t.NumIn() == 0 {
function := reflect.ValueOf(f)
in := make([]reflect.Value, 0)
out := function.Call(in)
if num := len(out); num > 0 {
list := make([]interface{}, num)
for i, value := range out {
list[i] = value.Interface()
}
if num == 1 {
return list[0]
}
return list
}
return nil
}
}
return f
}
func isZero(f interface{}) bool {
v := reflect.ValueOf(f)
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.String:
str := v.String()
if str == "" {
return true
}
zero, error := strconv.ParseFloat(str, 10)
if zero == 0 && error == nil {
return true
}
boolean, error := strconv.ParseBool(str)
return boolean == false && error == nil
default:
return false
}
}
// TestFnTime run func use time
func TestFnTime(f interface{}) string {
start := time.Now()
callFn(f)
end := time.Now()
vf := reflect.ValueOf(f)
str := fmt.Sprintf("[%s] runtime: %v\n", runtime.FuncForPC(vf.Pointer()).Name(), end.Sub(start))
fmt.Println(str)
return str
}
// If - (a ? b : c) Or (a && b)
func If(args ...interface{}) interface{} {
var condition = callFn(args[0])
if len(args) == 1 {
return condition
}
var trueVal = args[1]
var falseVal interface{}
if len(args) > 2 {
falseVal = args[2]
} else {
falseVal = nil
}
if condition == nil {
return callFn(falseVal)
} else if v, ok := condition.(bool); ok {
if v == false {
return callFn(falseVal)
}
} else if isZero(condition) {
return callFn(falseVal)
} else if v, ok := condition.(error); ok {
if v != nil {
fmt.Println(v)
return condition
}
}
return callFn(trueVal)
}
// Or - (a || b)
func Or(args ...interface{}) interface{} {
var condition = callFn(args[0])
if len(args) == 1 {
return condition
}
if condition == nil {
return callFn(args[1])
}
if v, ok := condition.(bool); ok {
if v == false {
return callFn(args[1])
}
} else if isZero(condition) {
return callFn(args[1])
} else if v, ok := condition.(error); ok {
if v != nil {
fmt.Println(v)
return condition
}
}
return condition
}