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

Add FromSlicePtr #442

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions type_manipulation.go
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
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