diff --git a/logic.go b/logic.go index ef603d3..73f71ea 100644 --- a/logic.go +++ b/logic.go @@ -23,6 +23,14 @@ func IfThen[T any](cond bool, a, b T) T { return b } +// IfThenExec returns a() if cond is true, else b() +func IfThenExec[T any](cond bool, a func() T, b func() T) T { + if cond { + return a() + } + return b() +} + // PtrAsValue returns the value of `v` if `v` is not `nil`, else def func PtrAsValue[T any](v *T, def T) T { if v == nil { diff --git a/logic_test.go b/logic_test.go index c415176..d4a5bc1 100644 --- a/logic_test.go +++ b/logic_test.go @@ -35,6 +35,11 @@ func TestLogic(t *testing.T) { assert.Equal(t, 2, IfThen(false, 1, 2)) }) + t.Run("IfThenExec", func(t *testing.T) { + assert.Equal(t, 1, IfThenExec(true, func() any { return 1 }, func() any { return 2 })) + assert.Equal(t, 2, IfThenExec(false, func() any { return 1 }, func() any { return 2 })) + }) + t.Run("PtrAsValue", func(t *testing.T) { assert.Equal(t, 1, PtrAsValue(&[]int{1}[0], 2)) assert.Equal(t, 2, PtrAsValue((*int)(nil), 2))