From 4b84359c0e9aa0aa92aba4aea74d29ee979b28a3 Mon Sep 17 00:00:00 2001 From: esafonov Date: Mon, 27 Nov 2023 02:20:35 +0700 Subject: [PATCH] slice --- collections/slice/slice.go | 13 +++++++++ collections/slice/slice_test.go | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/collections/slice/slice.go b/collections/slice/slice.go index 28a705d..fb21a5d 100644 --- a/collections/slice/slice.go +++ b/collections/slice/slice.go @@ -728,3 +728,16 @@ func SortDesc[T constraints.Ordered](s []T) { func FitIndex[T any](index int, s []T) int { return math.MustBetween(index, 0, len(s)-1) } + +// Last returns last element. It panics if slice has zero length. +func Last[T constraints.Ordered](s []T) T { + return s[len(s)-1] +} + +// LastExists returns last element. +func LastExists[T constraints.Ordered](s []T) (element T, exists bool) { + if len(s) == 0 { + return ptr.Zero[T](), false + } + return s[len(s)-1], true +} diff --git a/collections/slice/slice_test.go b/collections/slice/slice_test.go index 60ad88a..7a3a599 100644 --- a/collections/slice/slice_test.go +++ b/collections/slice/slice_test.go @@ -892,3 +892,55 @@ func ExampleFitIndex() { // 1 // -1 } + +func ExampleLast() { + fmt.Println(Last([]int{10, 20, 30})) + + // Output: + // 30 +} + +func TestLast_Panic(t *testing.T) { + t.Parallel() + for i, s := range [][]int{nil, {}} { + s := s + t.Run(strconv.Itoa(i), func(t *testing.T) { + t.Parallel() + defer func() { + if r := recover(); r == nil { + t.Error("must panic") + } + }() + Last(s) + }) + } +} + +func ExampleLastExists() { + fmt.Println(LastExists([]int{10, 20, 30})) + fmt.Println(LastExists([]int{})) + fmt.Println(LastExists[int](nil)) + + // Output: + // 30 true + // 0 false + // 0 false +} + +func ExampleSort() { + s := []int{10, 120, 30} + Sort(s) + fmt.Println(s) + + // Output: + // [10 30 120] +} + +func ExampleSortDesc() { + s := []int{10, 120, 30} + SortDesc(s) + fmt.Println(s) + + // Output: + // [10 30 120] +}