Skip to content

Commit

Permalink
Add FromPtrOr (#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
CorentinClabaut committed Jul 24, 2022
1 parent af87abb commit 8290287
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Expand Up @@ -176,6 +176,7 @@ Type manipulation helpers:

- [ToPtr](#toptr)
- [FromPtr](#fromptr)
- [FromPtrOr](#fromptror)
- [ToSlicePtr](#tosliceptr)
- [ToAnySlice](#toanyslice)
- [FromAnySlice](#fromanyslice)
Expand Down Expand Up @@ -1519,6 +1520,19 @@ value := lo.FromPtr[string](nil)
// ""
```

### FromPtrOr

Returns the pointer value or the fallback value.

```go
str := "hello world"
value := lo.FromPtrOr[string](&str, "empty")
// "hello world"

value := lo.FromPtrOr[string](nil, "empty")
// "empty"
```

### ToSlicePtr

Returns a slice of pointer copy of value.
Expand Down
9 changes: 9 additions & 0 deletions type_manipulation.go
Expand Up @@ -14,6 +14,15 @@ func FromPtr[T any](x *T) T {
return *x
}

// FromPtrOr returns the pointer value or the fallback value.
func FromPtrOr[T any](x *T, fallback T) T {
if x == nil {
return fallback
}

return *x
}

// ToSlicePtr returns a slice of pointer copy of value.
func ToSlicePtr[T any](collection []T) []*T {
return Map(collection, func(x T, _ int) *T {
Expand Down
17 changes: 17 additions & 0 deletions type_manipulation_test.go
Expand Up @@ -27,6 +27,23 @@ func TestFromPtr(t *testing.T) {
is.EqualValues(ptr, FromPtr(&ptr))
}

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

const fallbackStr = "fallback"
str := "foo"
ptrStr := &str

const fallbackInt = -1
i := 9
ptrInt := &i

is.Equal(str, FromPtrOr(ptrStr, fallbackStr))
is.Equal(fallbackStr, FromPtrOr(nil, fallbackStr))
is.Equal(i, FromPtrOr(ptrInt, fallbackInt))
is.Equal(fallbackInt, FromPtrOr(nil, fallbackInt))
}

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

Expand Down

0 comments on commit 8290287

Please sign in to comment.