mirror of
https://github.com/samber/lo.git
synced 2025-09-26 20:11:13 +08:00
feat: add TernaryF function (#214)
* feat: add TernaryF function * docs: update example function to be more concise
This commit is contained in:
17
README.md
17
README.md
@@ -1548,6 +1548,23 @@ result := lo.Ternary[string](false, "a", "b")
|
||||
// "b"
|
||||
```
|
||||
|
||||
### TernaryF
|
||||
|
||||
```go
|
||||
result := lo.TernaryF[string](true, func() string { return "a" }, func() string { return "b" })
|
||||
// "a"
|
||||
|
||||
result := lo.TernaryF[string](false, func() string { return "a" }, func() string { return "b" })
|
||||
// "b"
|
||||
```
|
||||
|
||||
Useful to avoid nil-pointer dereferencing in intializations, or avoid running unnecessary code
|
||||
|
||||
```go
|
||||
var s *string
|
||||
someStr := TernaryF[string](s.Val == nil, func() string { return uuid.New().String() }, func() string { return *s })
|
||||
```
|
||||
|
||||
### If / ElseIf / Else
|
||||
|
||||
```go
|
||||
|
@@ -9,6 +9,14 @@ func Ternary[T any](condition bool, ifOutput T, elseOutput T) T {
|
||||
return elseOutput
|
||||
}
|
||||
|
||||
// TernaryF is a 1 line if/else statement whose options are functions
|
||||
func TernaryF[T any](condition bool, ifFunc func() T, elseFunc func() T) T {
|
||||
if condition {
|
||||
return ifFunc()
|
||||
}
|
||||
return elseFunc()
|
||||
}
|
||||
|
||||
type ifElse[T any] struct {
|
||||
result T
|
||||
done bool
|
||||
|
@@ -17,6 +17,16 @@ func TestTernary(t *testing.T) {
|
||||
is.Equal(result2, "b")
|
||||
}
|
||||
|
||||
func TestTernaryF(t *testing.T) {
|
||||
is := assert.New(t)
|
||||
|
||||
result1 := TernaryF(true, func() string { return "a" }, func() string { return "b" })
|
||||
result2 := TernaryF(false, func() string { return "a" }, func() string { return "b" })
|
||||
|
||||
is.Equal(result1, "a")
|
||||
is.Equal(result2, "b")
|
||||
}
|
||||
|
||||
func TestIfElse(t *testing.T) {
|
||||
t.Parallel()
|
||||
is := assert.New(t)
|
||||
|
Reference in New Issue
Block a user