From 7c3e1cd8b531a9ca27599382ba345415e6123d83 Mon Sep 17 00:00:00 2001 From: Samuel Berthe Date: Thu, 27 Jun 2024 15:27:51 +0200 Subject: [PATCH] feat: adding CoalesceOrEmpty --- README.md | 18 ++++++++++++++++++ type_manipulation.go | 6 ++++++ type_manipulation_test.go | 40 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/README.md b/README.md index ed16c7aa..a3d51faa 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ Type manipulation helpers: - [IsEmpty](#isempty) - [IsNotEmpty](#isnotempty) - [Coalesce](#coalesce) +- [CoalesceOrEmpty](#coalesceorempty) Function helpers: @@ -2479,6 +2480,23 @@ result, ok := lo.Coalesce(nil, nilStr, &str) // &"foobar" true ``` +### CoalesceOrEmpty + +Returns the first non-empty arguments. Arguments must be comparable. + +```go +result := lo.CoalesceOrEmpty(0, 1, 2, 3) +// 1 + +result := lo.CoalesceOrEmpty("") +// "" + +var nilStr *string +str := "foobar" +result := lo.CoalesceOrEmpty(nil, nilStr, &str) +// &"foobar" +``` + ### Partial Returns new function that, when called, has its first argument set to the provided value. diff --git a/type_manipulation.go b/type_manipulation.go index 83fad2e2..3a870f1b 100644 --- a/type_manipulation.go +++ b/type_manipulation.go @@ -109,3 +109,9 @@ func Coalesce[T comparable](v ...T) (result T, ok bool) { return } + +// CoalesceOrEmpty returns the first non-empty arguments. Arguments must be comparable. +func CoalesceOrEmpty[T comparable](v ...T) T { + result, _ := Coalesce(v...) + return result +} diff --git a/type_manipulation_test.go b/type_manipulation_test.go index 4ed6cb57..57bf960c 100644 --- a/type_manipulation_test.go +++ b/type_manipulation_test.go @@ -233,3 +233,43 @@ func TestCoalesce(t *testing.T) { is.Equal(result10, struct1) is.True(ok10) } + +func TestCoalesceOrEmpty(t *testing.T) { + t.Parallel() + is := assert.New(t) + + newStr := func(v string) *string { return &v } + var nilStr *string + str1 := newStr("str1") + str2 := newStr("str2") + + type structType struct { + field1 int + field2 float64 + } + var zeroStruct structType + struct1 := structType{1, 1.0} + struct2 := structType{2, 2.0} + + result1 := CoalesceOrEmpty[int]() + result2 := CoalesceOrEmpty(3) + result3 := CoalesceOrEmpty(nil, nilStr) + result4 := CoalesceOrEmpty(nilStr, str1) + result5 := CoalesceOrEmpty(nilStr, str1, str2) + result6 := CoalesceOrEmpty(str1, str2, nilStr) + result7 := CoalesceOrEmpty(0, 1, 2, 3) + result8 := CoalesceOrEmpty(zeroStruct) + result9 := CoalesceOrEmpty(zeroStruct, struct1) + result10 := CoalesceOrEmpty(zeroStruct, struct1, struct2) + + is.Equal(0, result1) + is.Equal(3, result2) + is.Nil(result3) + is.Equal(str1, result4) + is.Equal(str1, result5) + is.Equal(str1, result6) + is.Equal(result7, 1) + is.Equal(result8, zeroStruct) + is.Equal(result9, struct1) + is.Equal(result10, struct1) +}