Skip to content

Commit

Permalink
feat: adding FromSlicePtrNotNil
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Jul 26, 2024
1 parent cb150f5 commit 0dabc9c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ Type manipulation helpers:
- [ToSlicePtr](#tosliceptr)
- [FromSlicePtr](#fromsliceptr)
- [FromSlicePtrOr](#fromsliceptror)
- [FromSlicePtrNotNil](#fromsliceptrnotnil)
- [ToAnySlice](#toanyslice)
- [FromAnySlice](#fromanyslice)
- [Empty](#empty)
Expand Down Expand Up @@ -2709,10 +2710,22 @@ Returns a slice with the pointer values or the fallback value.
str1 := "hello"
str2 := "world"

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

### FromSlicePtrNotNil

Returns a slice with the pointer values without nil elements.

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

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

### ToAnySlice

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

// FromSlicePtr returns a slice with the pointer values or the fallback value.
// FromSlicePtrOr 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 {
Expand All @@ -79,6 +79,16 @@ func FromSlicePtrOr[T any](collection []*T, fallback T) []T {
})
}

// FromSlicePtrNotNil returns a slice with the pointer values without nil elements.
func FromSlicePtrNotNil[T any](collection []*T) []T {
return FilterMap(collection, func(x *T, _ int) (T, bool) {
if x == nil {
return Empty[T](), false
}
return *x, true
})
}

// 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 @@ -141,6 +141,16 @@ func TestFromSlicePtrOr(t *testing.T) {
is.Equal(result1, []string{str1, str2, "fallback"})
}

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

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

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

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

0 comments on commit 0dabc9c

Please sign in to comment.