-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathto_bool.go
More file actions
55 lines (45 loc) · 1.08 KB
/
to_bool.go
File metadata and controls
55 lines (45 loc) · 1.08 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
package functools
import (
"reflect"
"errors"
)
/*
'ToBool' function returns 'true' if numeric 'value' parameter isn't equal to zero,
string or iterable collections aren't empty, and for bool 'value' parameter it returns
original value.
ToBool(value) bool
ToBoolSafe(value) (bool, err)
*/
func toBool(value interface{}) bool {
if value == nil {
return false
}
rv := reflect.ValueOf(value)
switch value.(type) {
case int, int8, int16, int32, int64:
return rv.Int() != 0
case uint, uint8, uint16, uint32, uint64:
return rv.Uint() != 0
case float32, float64:
return rv.Float() != 0.0
case string:
return rv.String() != ""
case bool:
return rv.Bool()
default:
k := rv.Type().Kind()
if k == reflect.Array || k == reflect.Slice || k == reflect.Map {
return rv.Len() > 0
}
raise(errors.New("Unexpected type (" + k.String() + ") of value"), "ToBool")
}
return false
}
func ToBool(value interface{}) bool {
return toBool(value)
}
func ToBoolSafe(value interface{}) (result bool, err error) {
defer except(&err)
result = toBool(value)
return
}