-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathnumber_type.go
82 lines (77 loc) · 2.16 KB
/
number_type.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
78
79
80
81
82
package helper
import (
"fmt"
"reflect"
"github.com/thomaspoignant/go-feature-flag/cmd/cli/generate/manifest/model"
)
func GetFlagTypeFromVariations(variations map[string]*interface{}) (model.FlagType, error) {
if variations == nil {
return "", fmt.Errorf("impossible to find type, no variations found")
}
variationTypes := make(map[model.FlagType]interface{}, len(variations))
for _, val := range variations {
if val == nil {
// we skip if value is nil
continue
}
vv := *val
switch vv.(type) {
case bool:
variationTypes[model.FlagTypeBoolean] = interface{}(nil)
case string:
variationTypes[model.FlagTypeString] = interface{}(nil)
case int:
variationTypes[model.FlagTypeInteger] = interface{}(nil)
case float64:
variationTypes[model.FlagTypeFloat] = interface{}(nil)
case map[string]interface{}:
variationTypes[model.FlagTypeObject] = interface{}(nil)
default:
// do nothing here
continue
}
}
// we found the type and return it
if len(variationTypes) == 1 {
for key := range variationTypes {
return key, nil
}
}
_, okFloat := variationTypes[model.FlagTypeFloat]
_, okInteger := variationTypes[model.FlagTypeInteger]
if len(variationTypes) == 2 && okInteger && okFloat {
// we need to check if it is a float or an integer
for _, v := range variations {
if v == nil {
// we skip if value is nil
continue
}
numberType, err := numberType(*v)
if err != nil {
return "", err
}
if numberType == "float" {
return model.FlagTypeFloat, nil
}
}
return model.FlagTypeInteger, nil
}
return "", fmt.Errorf("impossible to find type")
}
func numberType(value interface{}) (string, error) {
val := reflect.ValueOf(value)
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "integer", nil
case reflect.Float32, reflect.Float64:
// Check if the float has a whole number value.
floatVal := val.Float()
if floatVal == float64(int64(floatVal)) {
return "integer", nil
}
return "float", nil
default:
return "", fmt.Errorf("unknown type %v", val.Kind())
}
}