-
Notifications
You must be signed in to change notification settings - Fork 0
/
typify.go
75 lines (66 loc) · 1.45 KB
/
typify.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 goramda
import (
"fmt"
)
func String(v interface{}) string {
switch v.(type) {
case byte:
return string(v.(byte))
case []byte:
return string(v.([]byte))
case string:
return v.(string)
case int, int32, int64, float64:
return fmt.Sprintf("%v", v)
default:
return ""
}
return ""
}
func Integer64(v interface{}) int64 {
if value, ok := v.(int64); ok {
return value
}
return int64(0)
}
func Integer32(v interface{}) int32 {
if value, ok := v.(int32); ok {
return value
}
return int32(0)
}
func Integer(v interface{}) int {
if value, ok := v.(int); ok {
return value
}
return int(0)
}
func IntSlice(v interface{}) []int {
if value, ok := v.([]int); ok {
return value
}
return []int{}
}
func StringSlice(v interface{}) []string {
if value, ok := v.([]string); ok {
return value
}
return []string{}
}
/* Typify converts v into default type t if it is nil
Typify(nil, 5) => returns 0
a := ClassA{name: "john"}
Typify(nil, a) => returns empty ClassA object
Typify(a, ClassA{}) => returns a
This function is to avoid condition checkings or panic errors of ramda method
that return nil values and replace nil into default value
that provided of default_type value
*/
func Typify(v interface{}, default_type interface{}) interface{} {
defaultType := getDefaultValueOf(default_type)
defaultValue := getDefaultValueOf(v)
if IsNil(v) || !Equals(defaultType, defaultValue) {
return defaultType
}
return v
}