-
Notifications
You must be signed in to change notification settings - Fork 94
/
jstype.go
74 lines (66 loc) · 1.43 KB
/
jstype.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
package xml2json
import (
"strconv"
"strings"
)
// https://cswr.github.io/JsonSchema/spec/basic_types/
// JSType is a JavaScript extracted from a string
type JSType int
const (
Bool JSType = iota
Int
Float
String
Null
)
// Str2JSType extract a JavaScript type from a string
func Str2JSType(s string) JSType {
var (
output JSType
)
s = strings.TrimSpace(s) // santize the given string
switch {
case isBool(s):
output = Bool
case isFloat(s):
output = Float
case isInt(s):
output = Int
case isNull(s):
output = Null
default:
output = String // if all alternatives have been eliminated, the input is a string
}
return output
}
func isBool(s string) bool {
return s == "true" || s == "false"
}
func isFloat(s string) bool {
var output = false
if strings.Contains(s, ".") {
_, err := strconv.ParseFloat(s, 64)
if err == nil { // the string successfully converts to a decimal
output = true
}
}
return output
}
func isInt(s string) bool {
var output = false
if len(s) >= 1 {
_, err := strconv.Atoi(s)
if err == nil { // the string successfully converts to an int
if s != "0" && s[0] == '0' {
// if the first rune is '0' and there is more than 1 rune, then the input is most likely a float or intended to be
// a string value -- such as in the case of a guid, or an international phone number
} else {
output = true
}
}
}
return output
}
func isNull(s string) bool {
return s == "null"
}