Skip to content

Commit

Permalink
feat: adding CoalesceOrEmpty (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
samber authored Jun 27, 2024
1 parent e5e4f02 commit 9999d6b
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ Type manipulation helpers:
- [IsEmpty](#isempty)
- [IsNotEmpty](#isnotempty)
- [Coalesce](#coalesce)
- [CoalesceOrEmpty](#coalesceorempty)

Function helpers:

Expand Down Expand Up @@ -2499,6 +2500,23 @@ result, ok := lo.Coalesce(nil, nilStr, &str)
// &"foobar" true
```

### CoalesceOrEmpty

Returns the first non-empty arguments. Arguments must be comparable.

```go
result := lo.CoalesceOrEmpty(0, 1, 2, 3)
// 1

result := lo.CoalesceOrEmpty("")
// ""

var nilStr *string
str := "foobar"
result := lo.CoalesceOrEmpty(nil, nilStr, &str)
// &"foobar"
```

### Partial

Returns new function that, when called, has its first argument set to the provided value.
Expand Down
6 changes: 6 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,9 @@ func Coalesce[T comparable](v ...T) (result T, ok bool) {

return
}

// CoalesceOrEmpty returns the first non-empty arguments. Arguments must be comparable.
func CoalesceOrEmpty[T comparable](v ...T) T {
result, _ := Coalesce(v...)
return result
}
40 changes: 40 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,43 @@ func TestCoalesce(t *testing.T) {
is.Equal(result10, struct1)
is.True(ok10)
}

func TestCoalesceOrEmpty(t *testing.T) {
t.Parallel()
is := assert.New(t)

newStr := func(v string) *string { return &v }
var nilStr *string
str1 := newStr("str1")
str2 := newStr("str2")

type structType struct {
field1 int
field2 float64
}
var zeroStruct structType
struct1 := structType{1, 1.0}
struct2 := structType{2, 2.0}

result1 := CoalesceOrEmpty[int]()
result2 := CoalesceOrEmpty(3)
result3 := CoalesceOrEmpty(nil, nilStr)
result4 := CoalesceOrEmpty(nilStr, str1)
result5 := CoalesceOrEmpty(nilStr, str1, str2)
result6 := CoalesceOrEmpty(str1, str2, nilStr)
result7 := CoalesceOrEmpty(0, 1, 2, 3)
result8 := CoalesceOrEmpty(zeroStruct)
result9 := CoalesceOrEmpty(zeroStruct, struct1)
result10 := CoalesceOrEmpty(zeroStruct, struct1, struct2)

is.Equal(0, result1)
is.Equal(3, result2)
is.Nil(result3)
is.Equal(str1, result4)
is.Equal(str1, result5)
is.Equal(str1, result6)
is.Equal(result7, 1)
is.Equal(result8, zeroStruct)
is.Equal(result9, struct1)
is.Equal(result10, struct1)
}

0 comments on commit 9999d6b

Please sign in to comment.