Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
1. 增加了一个条件判断执行对应方法的函数;
2. 调整和增加单元测试和Example;
  • Loading branch information
bigdavidwong committed Nov 2, 2024
1 parent 69855ce commit 16e4422
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
12 changes: 10 additions & 2 deletions condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,19 @@

package ekit

// IfThenElse 根据条件返回对应的泛型结果,请注意,结果值在传入时就会访问,请务必确认其合法性
// 例:传 trueValue 时传入了一个指针对象并调用其方法,需要先判空
// IfThenElse 根据条件返回对应的泛型结果
// 注意避免结果的空指针问题
func IfThenElse[T any](condition bool, trueValue, falseValue T) T {
if condition {
return trueValue
}
return falseValue
}

// IfThenElseFunc 根据条件执行对应的函数并返回泛型结果
func IfThenElseFunc[T any](condition bool, trueFunc, falseFunc func() T) T {
if condition {
return trueFunc()
}
return falseFunc()
}
35 changes: 35 additions & 0 deletions condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package ekit

import (
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -25,3 +27,36 @@ func TestIfThenElse(t *testing.T) {
i = IfThenElse(false, i, 0)
assert.Equal(t, i, 0)
}

func ExampleIfThenElse() {
result := IfThenElse(true, "yes", "no")
fmt.Println(result)

// Output:
// yes
}

func TestIfThenElseFunc(t *testing.T) {
err := IfThenElseFunc(true, func() error {
return nil
}, func() error {
return errors.New("some error")
})
assert.NoError(t, err)
}

func ExampleIfThenElseFunc() {
err := IfThenElseFunc(false, func() error {
// do something when condition is true
// ...
return nil
}, func() error {
// do something when condition is false
// ...
return errors.New("some error when execute func2")
})
fmt.Println(err)

// Output:
// some error when execute func2
}

0 comments on commit 16e4422

Please sign in to comment.