Skip to content

Commit

Permalink
Last and Nth return errors
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Mar 3, 2022
1 parent a591377 commit 4e339ad
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ min := lo.Max[int]([]int{})

### Last

Returns the last element of a collection or panics if empty.
Returns the last element of a collection or error if empty.

```go
last, err := lo.Last[int]([]int{1, 2, 3})
Expand All @@ -477,7 +477,7 @@ last, err := lo.Last[int]([]int{1, 2, 3})

### Nth

Returns the element at index `nth` of collection. If `nth` is negative, the nth element from the end is returned.
Returns the element at index `nth` of collection. If `nth` is negative, the nth element from the end is returned. An error is returned when nth is out of slice bounds.

```go
nth, err := lo.Nth[int]([]int{0, 1, 2, 3}, 2)
Expand Down
5 changes: 3 additions & 2 deletions find.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func Max[T Ordered](collection []T) T {
return max
}

// Last returns the last element of a collection or panics if empty.
// Last returns the last element of a collection or error if empty.
func Last[T any](collection []T) (T, error) {
length := len(collection)

Expand All @@ -98,7 +98,8 @@ func Last[T any](collection []T) (T, error) {
return collection[length-1], nil
}

// Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element from the end is returned.
// Nth returns the element at index `nth` of collection. If `nth` is negative, the nth element
// from the end is returned. An error is returned when nth is out of slice bounds.
func Nth[T any](collection []T, nth int) (T, error) {
if int(math.Abs(float64(nth))) > len(collection) {
var t T
Expand Down

0 comments on commit 4e339ad

Please sign in to comment.