forked from mlogclub/simple
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathternary_expression.go
More file actions
85 lines (81 loc) · 1.78 KB
/
Copy pathternary_expression.go
File metadata and controls
85 lines (81 loc) · 1.78 KB
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
// 实现简单的三元表达式功能
package simple
import (
"reflect"
"strconv"
)
// 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 isFalse(condition) {
return callFn(falseVal)
} else if v, ok := condition.(error); ok {
if v != nil {
return condition
}
}
return callFn(trueVal)
}
func isFalse(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, err := strconv.ParseFloat(str, 10)
if zero == 0 && err == nil {
return true
}
boolean, err := strconv.ParseBool(str)
return boolean == false && err == nil
default:
return false
}
}
// 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
}