Commit 7db4be57 authored by Aaron Raddon's avatar Aaron Raddon

CoerceFloats

parent a86c2d2e
......@@ -72,7 +72,10 @@ func CoerceStrings(v interface{}) []string {
case string:
sva = append(sva, aval)
default:
//Warnf("Kind ? %T v=%v", aval, aval)
sv, err := CoerceString(av)
if err == nil && sv != "" {
sva = append(sva, sv)
}
}
}
return sva
......@@ -80,6 +83,41 @@ func CoerceStrings(v interface{}) []string {
return []string{CoerceStringShort(v)}
}
func CoerceFloats(v interface{}) []float64 {
switch val := v.(type) {
case float64:
return []float64{val}
case []string:
fa := make([]float64, 0)
for _, av := range val {
f, err := CoerceFloat(av)
if err == nil && !math.IsNaN(f) {
fa = append(fa, f)
}
}
return fa
case []interface{}:
fa := make([]float64, 0)
for _, av := range val {
switch aval := av.(type) {
case float64:
fa = append(fa, aval)
default:
f, err := CoerceFloat(av)
if err == nil && !math.IsNaN(f) {
fa = append(fa, f)
}
}
}
return fa
}
fv, err := CoerceFloat(v)
if err == nil {
return []float64{fv}
}
return nil
}
func CoerceFloat(v interface{}) (float64, error) {
switch val := v.(type) {
case int:
......
......@@ -28,6 +28,9 @@ func TestCoerce(t *testing.T) {
assert.True(t, CoerceIntShort(data["stringf"]) == 22, "get stringf as int: %v", data["stringf"])
assert.Equal(t, 0, len(CoerceStrings(data["emptystring"])), "get emptystring as []string: %v", data["emptystring"])
assert.Equal(t, []string{"22"}, CoerceStrings(data["string"]), "get string as []string: %v", data["emptystring"])
assert.Equal(t, []string{"4"}, CoerceStrings(data["int"]), "get int as []string: %v", data["emptystring"])
assert.Equal(t, []string{"22"}, CoerceStrings(data["string"]), "get string as []string: %v", data["string"])
assert.Equal(t, []string{"4"}, CoerceStrings(data["int"]), "get int as []string: %v", data["int"])
assert.Equal(t, []float64{float64(4)}, CoerceFloats(data["int"]), "get int as []float64: %v", data["int"])
assert.Equal(t, []float64{float64(45.3)}, CoerceFloats(data["float"]), "get float as []float64: %v", data["float"])
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment