Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding FromSlicePtrOr #506

Merged
merged 1 commit into from
Jul 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ Type manipulation helpers:
- [FromPtrOr](#fromptror)
- [ToSlicePtr](#tosliceptr)
- [FromSlicePtr](#fromsliceptr)
- [FromSlicePtrOr](#fromsliceptror)
- [ToAnySlice](#toanyslice)
- [FromAnySlice](#fromanyslice)
- [Empty](#empty)
Expand Down Expand Up @@ -2700,6 +2701,18 @@ ptr := lo.Compact(
// []string{"hello", "world"}
```

### FromSlicePtrOr

Returns a slice with the pointer values or the fallback value.

```go
str1 := "hello"
str2 := "world"

ptr := lo.FromSlicePtrOr[string]([]*string{&str1, &str2, "fallback value"})
// []string{"hello", "world", "fallback value"}
```

### ToAnySlice

Returns a slice with all elements mapped to `any` type.
Expand Down
10 changes: 10 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ func FromSlicePtr[T any](collection []*T) []T {
})
}

// FromSlicePtr returns a slice with the pointer values or the fallback value.
func FromSlicePtrOr[T any](collection []*T, fallback T) []T {
return Map(collection, func(x *T, _ int) T {
if x == nil {
return fallback
}
return *x
})
}

// ToAnySlice returns a slice with all elements mapped to `any` type
func ToAnySlice[T any](collection []T) []any {
result := make([]any, len(collection))
Expand Down
10 changes: 10 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,16 @@ func TestFromSlicePtr(t *testing.T) {
is.Equal(result1, []string{str1, str2, ""})
}

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

str1 := "foo"
str2 := "bar"
result1 := FromSlicePtrOr([]*string{&str1, &str2, nil}, "fallback")

is.Equal(result1, []string{str1, str2, "fallback"})
}

func TestToAnySlice(t *testing.T) {
t.Parallel()
is := assert.New(t)
Expand Down
Loading