Skip to content

Commit 6c6da2c

Browse files
feat: add TernaryF function (#214)
* feat: add TernaryF function * docs: update example function to be more concise
1 parent bcb54cc commit 6c6da2c

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1548,6 +1548,23 @@ result := lo.Ternary[string](false, "a", "b")
15481548
// "b"
15491549
```
15501550

1551+
### TernaryF
1552+
1553+
```go
1554+
result := lo.TernaryF[string](true, func() string { return "a" }, func() string { return "b" })
1555+
// "a"
1556+
1557+
result := lo.TernaryF[string](false, func() string { return "a" }, func() string { return "b" })
1558+
// "b"
1559+
```
1560+
1561+
Useful to avoid nil-pointer dereferencing in intializations, or avoid running unnecessary code
1562+
1563+
```go
1564+
var s *string
1565+
someStr := TernaryF[string](s.Val == nil, func() string { return uuid.New().String() }, func() string { return *s })
1566+
```
1567+
15511568
### If / ElseIf / Else
15521569

15531570
```go

condition.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ func Ternary[T any](condition bool, ifOutput T, elseOutput T) T {
99
return elseOutput
1010
}
1111

12+
// TernaryF is a 1 line if/else statement whose options are functions
13+
func TernaryF[T any](condition bool, ifFunc func() T, elseFunc func() T) T {
14+
if condition {
15+
return ifFunc()
16+
}
17+
return elseFunc()
18+
}
19+
1220
type ifElse[T any] struct {
1321
result T
1422
done bool

condition_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,16 @@ func TestTernary(t *testing.T) {
1717
is.Equal(result2, "b")
1818
}
1919

20+
func TestTernaryF(t *testing.T) {
21+
is := assert.New(t)
22+
23+
result1 := TernaryF(true, func() string { return "a" }, func() string { return "b" })
24+
result2 := TernaryF(false, func() string { return "a" }, func() string { return "b" })
25+
26+
is.Equal(result1, "a")
27+
is.Equal(result2, "b")
28+
}
29+
2030
func TestIfElse(t *testing.T) {
2131
t.Parallel()
2232
is := assert.New(t)

0 commit comments

Comments
 (0)