From 6c6da2c66ca356f3ffd08fd22ac3f0d8a948b3fe Mon Sep 17 00:00:00 2001 From: Nic Johnson Date: Sun, 2 Oct 2022 17:56:41 -0500 Subject: [PATCH] feat: add TernaryF function (#214) * feat: add TernaryF function * docs: update example function to be more concise --- README.md | 17 +++++++++++++++++ condition.go | 8 ++++++++ condition_test.go | 10 ++++++++++ 3 files changed, 35 insertions(+) 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)