Add ToIntSlice

This commit is contained in:
bep 2015-02-24 11:58:16 +01:00
parent 2318c5caf2
commit 5db8dfc0bf
3 changed files with 32 additions and 0 deletions

View File

@ -56,3 +56,8 @@ func ToStringSlice(i interface{}) []string {
v, _ := ToStringSliceE(i) v, _ := ToStringSliceE(i)
return v return v
} }
func ToIntSlice(i interface{}) []int {
v, _ := ToIntSliceE(i)
return v
}

View File

@ -77,6 +77,13 @@ func TestMaps(t *testing.T) {
assert.Equal(t, ToStringMapBool(stringMapBool), map[string]bool{"v1": true, "v2": false}) assert.Equal(t, ToStringMapBool(stringMapBool), map[string]bool{"v1": true, "v2": false})
} }
func TestSlices(t *testing.T) {
assert.Equal(t, []string{"a", "b"}, ToStringSlice([]string{"a", "b"}))
assert.Equal(t, []string{"1", "3"}, ToStringSlice([]interface{}{1, 3}))
assert.Equal(t, []int{1, 3}, ToIntSlice([]int{1, 3}))
assert.Equal(t, []int{1, 3}, ToIntSlice([]interface{}{1.2, 3.2}))
}
func TestToBool(t *testing.T) { func TestToBool(t *testing.T) {
assert.Equal(t, ToBool(0), false) assert.Equal(t, ToBool(0), false)
assert.Equal(t, ToBool(nil), false) assert.Equal(t, ToBool(nil), false)

View File

@ -299,6 +299,26 @@ func ToStringSliceE(i interface{}) ([]string, error) {
return a, fmt.Errorf("Unable to Cast %#v to []string", i) return a, fmt.Errorf("Unable to Cast %#v to []string", i)
} }
func ToIntSliceE(i interface{}) ([]int, error) {
jww.DEBUG.Println("ToIntSliceE called on type:", reflect.TypeOf(i))
var a []int
switch v := i.(type) {
case []interface{}:
for _, u := range v {
a = append(a, ToInt(u))
}
return a, nil
case []int:
return v, nil
default:
return a, fmt.Errorf("Unable to Cast %#v to []int", i)
}
return a, fmt.Errorf("Unable to Cast %#v to []int", i)
}
func StringToDate(s string) (time.Time, error) { func StringToDate(s string) (time.Time, error) {
return parseDateWith(s, []string{ return parseDateWith(s, []string{
time.RFC3339, time.RFC3339,