Skip to content

Commit

Permalink
slice
Browse files Browse the repository at this point in the history
  • Loading branch information
esafonov committed Nov 26, 2023
1 parent 6cf7026 commit 4b84359
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
13 changes: 13 additions & 0 deletions collections/slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
52 changes: 52 additions & 0 deletions collections/slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
}

0 comments on commit 4b84359

Please sign in to comment.