From f86c4faeb605b705a1696e9b81f875821408f137 Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Fri, 26 Jul 2024 07:54:24 +0200 Subject: [PATCH] feat: adding FromSlicePtrOr --- README.md | 13 +++++++++++++ type_manipulation.go | 10 ++++++++++ type_manipulation_test.go | 10 ++++++++++ 3 files changed, 33 insertions(+) diff --git a/README.md b/README.md index 2d92c422..3751b339 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,7 @@ Type manipulation helpers: - [FromPtrOr](#fromptror) - [ToSlicePtr](#tosliceptr) - [FromSlicePtr](#fromsliceptr) +- [FromSlicePtrOr](#fromsliceptror) - [ToAnySlice](#toanyslice) - [FromAnySlice](#fromanyslice) - [Empty](#empty) @@ -2700,6 +2701,18 @@ ptr := lo.Compact( // []string{"hello", "world"} ``` +### FromSlicePtrOr + +Returns a slice with the pointer values or the fallback value. + +```go +str1 := "hello" +str2 := "world" + +ptr := lo.FromSlicePtrOr[string]([]*string{&str1, &str2, "fallback value"}) +// []string{"hello", "world", "fallback value"} +``` + ### ToAnySlice Returns a slice with all elements mapped to `any` type. diff --git a/type_manipulation.go b/type_manipulation.go index 27fa6e75..ef070281 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -69,6 +69,16 @@ func FromSlicePtr[T any](collection []*T) []T { }) } +// FromSlicePtr 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 { + return fallback + } + 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 f0d2567f..3a7d3145 100644 --- a/type_manipulation_test.go +++ b/type_manipulation_test.go @@ -131,6 +131,16 @@ func TestFromSlicePtr(t *testing.T) { is.Equal(result1, []string{str1, str2, ""}) } +func TestFromSlicePtrOr(t *testing.T) { + is := assert.New(t) + + str1 := "foo" + str2 := "bar" + result1 := FromSlicePtrOr([]*string{&str1, &str2, nil}, "fallback") + + is.Equal(result1, []string{str1, str2, "fallback"}) +} + func TestToAnySlice(t *testing.T) { t.Parallel() is := assert.New(t)