Skip to content

Commit

Permalink
fix: The LastIndexOf method can never return the index of the first e…
Browse files Browse the repository at this point in the history
…lement (duke-git#83)

Co-authored-by: JiangCheng <[email protected]>
  • Loading branch information
Mickls and JiangCheng authored Mar 28, 2023
1 parent f09e521 commit 3b49753
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
2 changes: 1 addition & 1 deletion slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -1094,7 +1094,7 @@ func IndexOf[T comparable](arr []T, val T) int {
// LastIndexOf returns the index at which the last occurrence of the item is found in a slice or return -1 if the then cannot be found.
// Play: https://go.dev/play/p/DokM4cf1IKH
func LastIndexOf[T comparable](slice []T, item T) int {
for i := len(slice) - 1; i > 0; i-- {
for i := len(slice) - 1; i >= 0; i-- {
if item == slice[i] {
return i
}
Expand Down
9 changes: 5 additions & 4 deletions slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -665,8 +665,8 @@ func TestDifferenceWith(t *testing.T) {
func TestDifferenceBy(t *testing.T) {
assert := internal.NewAssert(t, "TestDifferenceBy")

s1 := []int{1, 2, 3, 4, 5} //after add one: 2 3 4 5 6
s2 := []int{3, 4, 5} //after add one: 4 5 6
s1 := []int{1, 2, 3, 4, 5} // after add one: 2 3 4 5 6
s2 := []int{3, 4, 5} // after add one: 4 5 6
addOne := func(i int, v int) int {
return v + 1
}
Expand Down Expand Up @@ -873,8 +873,9 @@ func TestIndexOf(t *testing.T) {
func TestLastIndexOf(t *testing.T) {
assert := internal.NewAssert(t, "TestLastIndexOf")

arr := []string{"a", "a", "b", "c"}
assert.Equal(1, LastIndexOf(arr, "a"))
arr := []string{"a", "b", "b", "c"}
assert.Equal(0, LastIndexOf(arr, "a"))
assert.Equal(2, LastIndexOf(arr, "b"))
assert.Equal(-1, LastIndexOf(arr, "d"))
}

Expand Down

0 comments on commit 3b49753

Please sign in to comment.