mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
fix: The LastIndexOf method can never return the index of the first element (#83)
Co-authored-by: JiangCheng <jiangcheng@kezaihui.com>
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user