From aa609e4f470e96044f34f91ab2b85683b0ceff24 Mon Sep 17 00:00:00 2001 From: Masakazu Ohtsuka Date: Fri, 26 Jul 2024 14:51:40 +0900 Subject: [PATCH] feat: add FromSlicePtr (#217) * feat: add FromSlicePtr * Update README.md --------- Co-authored-by: Samuel Berthe --- README.md | 19 +++++++++++++++++++ type_manipulation.go | 11 +++++++++++ type_manipulation_test.go | 10 ++++++++++ 3 files changed, 40 insertions(+) diff --git a/README.md b/README.md index ea94a528..2d92c422 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,7 @@ Type manipulation helpers: - [FromPtr](#fromptr) - [FromPtrOr](#fromptror) - [ToSlicePtr](#tosliceptr) +- [FromSlicePtr](#fromsliceptr) - [ToAnySlice](#toanyslice) - [FromAnySlice](#fromanyslice) - [Empty](#empty) @@ -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. diff --git a/type_manipulation.go b/type_manipulation.go index 3e965183..27fa6e75 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -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)) diff --git a/type_manipulation_test.go b/type_manipulation_test.go index 61e21f52..f0d2567f 100644 --- a/type_manipulation_test.go +++ b/type_manipulation_test.go @@ -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)