Skip to content

Commit

Permalink
Add IfThenExec function to logic package
Browse files Browse the repository at this point in the history
  • Loading branch information
demdxx committed Apr 18, 2024
1 parent 5ae00de commit b552a10
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
8 changes: 8 additions & 0 deletions logic.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions logic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down

0 comments on commit b552a10

Please sign in to comment.