feat: add TernaryF function (#214)

* feat: add TernaryF function

* docs: update example function to be more concise
This commit is contained in:
Nic Johnson
2022-10-02 17:56:41 -05:00
committed by GitHub
parent bcb54ccf0b
commit 6c6da2c66c
3 changed files with 35 additions and 0 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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)