Skip to content

Commit

Permalink
feat: add FromSlicePtr (#217)
Browse files Browse the repository at this point in the history
* feat: add FromSlicePtr

* Update README.md

---------

Co-authored-by: Samuel Berthe <dev@samuel-berthe.fr>
  • Loading branch information
mash and samber authored Jul 26, 2024
1 parent df28bdd commit aa609e4
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ Type manipulation helpers:
- [FromPtr](#fromptr)
- [FromPtrOr](#fromptror)
- [ToSlicePtr](#tosliceptr)
- [FromSlicePtr](#fromsliceptr)
- [ToAnySlice](#toanyslice)
- [FromAnySlice](#fromanyslice)
- [Empty](#empty)
Expand Down Expand Up @@ -2681,6 +2682,24 @@ ptr := lo.ToSlicePtr([]string{"hello", "world"})
// []*string{"hello", "world"}
```

### FromSlicePtr

Returns a slice with the pointer values.
Returns a zero value in case of a nil pointer element.

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

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

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

### ToAnySlice

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

// FromSlicePtr returns a slice with the pointer values.
// Returns a zero value in case of a nil pointer element.
func FromSlicePtr[T any](collection []*T) []T {
return Map(collection, func(x *T, _ int) T {
if x == nil {
return Empty[T]()
}
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 @@ -121,6 +121,16 @@ func TestToSlicePtr(t *testing.T) {
is.Equal(result1, []*string{&str1, &str2})
}

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

str1 := "foo"
str2 := "bar"
result1 := FromSlicePtr([]*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 aa609e4

Please sign in to comment.