Skip to content

Commit

Permalink
feat: add TernaryF function (#214)
Browse files Browse the repository at this point in the history
* feat: add TernaryF function

* docs: update example function to be more concise
  • Loading branch information
nicjohnson145 authored Oct 2, 2022
1 parent bcb54cc commit 6c6da2c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions condition.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions condition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 6c6da2c

Please sign in to comment.