Skip to content

Commit

Permalink
Add FromSlicePtr
Browse files Browse the repository at this point in the history
  • Loading branch information
KenxinKun committed Apr 17, 2024
1 parent 71d8341 commit e202682
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
10 changes: 10 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ func FromPtrOr[T any](x *T, fallback T) T {
return *x
}

// FromSlicePtr returns a slice of value filtering any nil pointers.
func FromSlicePtr[T any](collection []*T) []T {
return FilterMap(collection, func(item *T, _ int) (T, bool) {
if item == nil {
return Empty[T](), false
}
return *item, true
})
}

// 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
11 changes: 11 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ func TestFromPtrOr(t *testing.T) {
is.Equal(fallbackInt, FromPtrOr(nil, fallbackInt))
}

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

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

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

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

0 comments on commit e202682

Please sign in to comment.