diff --git a/README.md b/README.md index 8fc3272f..0799f8ab 100644 --- a/README.md +++ b/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 diff --git a/condition.go b/condition.go index 6fd31f1e..80de6644 100644 --- a/condition.go +++ b/condition.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 diff --git a/condition_test.go b/condition_test.go index 85cea19f..ffb1e542 100644 --- a/condition_test.go +++ b/condition_test.go @@ -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)