forked from aliuygur/godash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathto.go
77 lines (68 loc) · 1.69 KB
/
to.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
package godash
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"unicode"
)
// ToString convert the input to a string.
func ToString(obj interface{}) string {
res := fmt.Sprintf("%v", obj)
return string(res)
}
// ToJSON convert the input to a valid JSON string
func ToJSON(obj interface{}) (string, error) {
res, err := json.Marshal(obj)
if err != nil {
res = []byte("")
}
return string(res), err
}
// ToFloat convert the input string to a float, or 0.0 if the input is not a float.
func ToFloat(str string) (float64, error) {
res, err := strconv.ParseFloat(str, 64)
if err != nil {
res = 0.0
}
return res, err
}
// ToInt convert the input string to an integer, or 0 if the input is not an integer.
func ToInt(str string) (int64, error) {
res, err := strconv.ParseInt(str, 0, 64)
if err != nil {
res = 0
}
return res, err
}
// ToBoolean convert the input string to a boolean.
func ToBoolean(str string) (bool, error) {
res, err := strconv.ParseBool(str)
if err != nil {
res = false
}
return res, err
}
// ToCamelCase converts from underscore separated form to camel case form.
func ToCamelCase(s string) string {
byteSrc := []byte(s)
chunks := rxCameling.FindAll(byteSrc, -1)
for idx, val := range chunks {
chunks[idx] = bytes.Title(val)
}
return string(bytes.Join(chunks, nil))
}
// ToSnakeCase converts from camel case form to underscore separated form.
func ToSnakeCase(s string) string {
s = ToCamelCase(s)
runes := []rune(s)
length := len(runes)
var out []rune
for i := 0; i < length; i++ {
out = append(out, unicode.ToLower(runes[i]))
if i+1 < length && (unicode.IsUpper(runes[i+1]) && unicode.IsLower(runes[i])) {
out = append(out, '_')
}
}
return string(out)
}