Skip to content

Commit

Permalink
add duration cast
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Charlot committed May 20, 2019
1 parent fba35dd commit e818efa
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
33 changes: 33 additions & 0 deletions cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,36 @@ func AsDatetimeArray(values ...interface{}) ([]time.Time, bool) {
}
return arr, b
}

// AsDuration to convert as a duration
func AsDuration(v interface{}) (time.Duration, bool) {
switch d := v.(type) {
case time.Duration:
return d, true
case int, int8, int16, int32, int64:
return time.Duration(reflect.ValueOf(d).Int()), true
case float32, float64:
return time.Duration(int64(reflect.ValueOf(d).Float())), true
case string:
if du, err := time.ParseDuration(d); err == nil {
return du, true
}
return time.Duration(0), false
default:
return time.Duration(0), false
}
}

// AsDurationArray to convert as an array of duration
func AsDurationArray(values ...interface{}) ([]time.Duration, bool) {
arr := make([]time.Duration, len(values))
b := true
for i, v := range values {
if cv, ok := AsDuration(v); ok {
arr[i] = cv
continue
}
b = false
}
return arr, b
}
27 changes: 27 additions & 0 deletions cast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,27 @@ func TestAsDatetimeArray(t *testing.T) {
assert.Equal(t, []time.Time{timestamp, date, datetime, {}}, arr)
}

func TestAsDuration(t *testing.T) {
duration := time.Second * 10

testDuration(t, duration, duration, true)
testDuration(t, 10000000000, duration, true)
testDuration(t, "10s", duration, true)
testDuration(t, "wrong", time.Duration(0), false)
}

func TestAsDurationArray(t *testing.T) {
duration := time.Second * 10

arr, ok := cast.AsDurationArray(duration, 10000000000, "10s")
assert.True(t, ok)
assert.Equal(t, []time.Duration{duration, duration, duration}, arr)

arr, ok = cast.AsDurationArray(duration, 10000000000, "10s", "wrong")
assert.False(t, ok)
assert.Equal(t, []time.Duration{duration, duration, duration, time.Duration(0)}, arr)
}

func testBool(t *testing.T, value interface{}, expected bool, ok bool) {
b, o := cast.AsBool(value)
assert.Equal(t, expected, b)
Expand Down Expand Up @@ -186,3 +207,9 @@ func testDatetime(t *testing.T, value interface{}, expected time.Time, ok bool)
assert.Equal(t, expected, b)
assert.Equal(t, ok, o)
}

func testDuration(t *testing.T, value interface{}, expected time.Duration, ok bool) {
b, o := cast.AsDuration(value)
assert.Equal(t, expected, b)
assert.Equal(t, ok, o)
}

0 comments on commit e818efa

Please sign in to comment.