From c7babfaa4607dbd25fb47c540605a664e02e8df6 Mon Sep 17 00:00:00 2001 From: Alireza Kiani Date: Fri, 28 Jun 2024 01:51:20 +0330 Subject: [PATCH] feat: follow convention for return items and reuse base First function and add FirstOr --- find.go | 26 +++++++++++++++----------- find_test.go | 29 ++++++++++++++++++++++------- 2 files changed, 37 insertions(+), 18 deletions(-) diff --git a/find.go b/find.go index 4fd62a99..58809288 100644 --- a/find.go +++ b/find.go @@ -367,28 +367,32 @@ func Last[T any](collection []T) (T, error) { return collection[length-1], nil } -// First returns the first element of a collection or error if empty. -func First[T any](collection []T) (T, error) { +// First returns the first element of a collection or zero if empty. +func First[T any](collection []T) (T, bool) { length := len(collection) if length == 0 { var t T - return t, fmt.Errorf("first: cannot extract the first element of an empty slice") + return t, false } - return collection[0], nil + return collection[0], true } -// FirstOrZeroValue returns the first element of a collection or zero value if empty. -func FirstOrZeroValue[T any](collection []T) T { - length := len(collection) +// FirstOrEmpty returns the first element of a collection or zero value if empty. +func FirstOrEmpty[T any](collection []T) T { + i, _ := First(collection) + return i +} - if length == 0 { - var t T - return t +// FirstOr returns the first element of a collection or the fallback value that is provided as the second argument. +func FirstOr[T any](collection []T, fallback T) T { + i, ok := First(collection) + if !ok { + return fallback } - return collection[0] + return i } // Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element diff --git a/find_test.go b/find_test.go index ff0898fc..8f9fe325 100644 --- a/find_test.go +++ b/find_test.go @@ -376,24 +376,39 @@ func TestFirst(t *testing.T) { t.Parallel() is := assert.New(t) - result1, err1 := First([]int{1, 2, 3}) - result2, err2 := First([]int{}) + result1, ok1 := First([]int{1, 2, 3}) + result2, ok2 := First([]int{}) is.Equal(result1, 1) - is.Equal(err1, nil) + is.Equal(ok1, true) is.Equal(result2, 0) - is.Equal(err2, fmt.Errorf("first: cannot extract the first element of an empty slice")) + is.Equal(ok2, false) } -func TestFirstOrZeroValue(t *testing.T) { +func TestFirstOrEmpty(t *testing.T) { t.Parallel() is := assert.New(t) - result1 := FirstOrZeroValue([]int{1, 2, 3}) - result2 := FirstOrZeroValue([]int{}) + result1 := FirstOrEmpty([]int{1, 2, 3}) + result2 := FirstOrEmpty([]int{}) + result3 := FirstOrEmpty([]string{}) is.Equal(result1, 1) is.Equal(result2, 0) + is.Equal(result3, "") +} + +func TestFirstOr(t *testing.T) { + t.Parallel() + is := assert.New(t) + + result1 := FirstOr([]int{1, 2, 3}, 63) + result2 := FirstOr([]int{}, 23) + result3 := FirstOr([]string{}, "test") + + is.Equal(result1, 1) + is.Equal(result2, 23) + is.Equal(result3, "test") } func TestNth(t *testing.T) {