File tree Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Expand file tree Collapse file tree 2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -57,3 +57,19 @@ func isPanic(fn func()) (err any) {
5757
5858 return
5959}
60+
61+ // isTrue checks whether a value is truthy or not. It'll return true if the value is not the zero
62+ // value for its type. For a slice, a truthy value should not be the zero value and the length must
63+ // be greater than 0. For nil, it'll always return false.
64+ func isTrue (v any ) bool {
65+ rv := reflect .ValueOf (v )
66+
67+ switch rv .Kind () {
68+ case reflect .Invalid :
69+ return false // always false
70+ case reflect .Slice :
71+ return v != nil && rv .Len () > 0
72+ default :
73+ return ! rv .IsZero ()
74+ }
75+ }
Original file line number Diff line number Diff line change @@ -41,3 +41,23 @@ func TestIsPanic(t *testing.T) {
4141 panic ("unexpected panic" )
4242 }))
4343}
44+
45+ func TestIsTrue (t * testing.T ) {
46+ assert := New (t )
47+
48+ // reflect.Invalid
49+ assert .DeepEqual (isTrue (nil ), false )
50+
51+ // reflect.Slice
52+ assert .DeepEqual (isTrue ([]int {0 }), true )
53+ assert .DeepEqual (isTrue ([]int {}), false )
54+
55+ // other kinds
56+ assert .DeepEqual (isTrue (1 ), true )
57+ assert .DeepEqual (isTrue (0 ), false )
58+ assert .DeepEqual (isTrue (1.0 ), true )
59+ assert .DeepEqual (isTrue (0.0 ), false )
60+ assert .DeepEqual (isTrue ("Hello" ), true )
61+ assert .DeepEqual (isTrue ("" ), false )
62+ assert .DeepEqual (isTrue (func () {}), true )
63+ }
You can’t perform that action at this time.
0 commit comments