Skip to content

Commit

Permalink
fix Nth
Browse files Browse the repository at this point in the history
  • Loading branch information
samber committed Mar 5, 2022
1 parent a482eff commit d90b852
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion find.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func Last[T any](collection []T) (T, error) {
// 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) {
if int(math.Abs(float64(nth))) >= len(collection) {
var t T
return t, fmt.Errorf("nth: %d out of slice bounds", nth)
}
Expand Down
6 changes: 6 additions & 0 deletions find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,17 @@ func TestNth(t *testing.T) {
result1, err1 := Nth[int]([]int{0, 1, 2, 3}, 2)
result2, err2 := Nth[int]([]int{0, 1, 2, 3}, -2)
result3, err3 := Nth[int]([]int{0, 1, 2, 3}, 42)
result4, err4 := Nth[int]([]int{}, 0)
result5, err5 := Nth[int]([]int{42}, 0)

is.Equal(result1, 2)
is.Equal(err1, nil)
is.Equal(result2, 2)
is.Equal(err2, nil)
is.Equal(result3, 0)
is.Equal(err3, fmt.Errorf("nth: 42 out of slice bounds"))
is.Equal(result4, 0)
is.Equal(err4, fmt.Errorf("nth: 0 out of slice bounds"))
is.Equal(result5, 42)
is.Equal(err5, nil)
}

0 comments on commit d90b852

Please sign in to comment.