1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

list: add LastIndexOf (#46)

Add LastIndexOf method too List and fix doc

LastIndexOf returns the index of the last occurrence of the value in this list.
if not found return -1
This commit is contained in:
donutloop
2022-07-21 09:19:18 +02:00
committed by GitHub
parent ac0fb5ef25
commit a82b5dd206
4 changed files with 61 additions and 3 deletions

View File

@@ -31,7 +31,7 @@ func (l *List[T]) ValueOf(index int) (*T, bool) {
return &l.data[index], true
}
// IndexOf reture the index of value. if not found return -1
// IndexOf returns the index of value. if not found return -1
func (l *List[T]) IndexOf(value T) int {
index := -1
data := l.data
@@ -44,6 +44,20 @@ func (l *List[T]) IndexOf(value T) int {
return index
}
// LastIndexOf returns the index of the last occurrence of the value in this list.
// if not found return -1
func (l *List[T]) LastIndexOf(value T) int {
index := -1
data := l.data
for i := len(data) - 1; i >= 0; i-- {
if reflect.DeepEqual(data[i], value) {
index = i
break
}
}
return index
}
// Contain checks if the value in the list or not
func (l *List[T]) Contain(value T) bool {
data := l.data

View File

@@ -36,6 +36,23 @@ func TestIndexOf(t *testing.T) {
assert.Equal(-1, i)
}
func TestLastIndexOf(t *testing.T) {
assert := internal.NewAssert(t, "TestIndexOf")
list := NewList([]int{1, 2, 3, 3, 3, 3, 4, 5, 6, 9})
i := list.LastIndexOf(3)
assert.Equal(5, i)
i = list.LastIndexOf(10)
assert.Equal(-1, i)
i = list.LastIndexOf(4)
assert.Equal(6, i)
i = list.LastIndexOf(1)
assert.Equal(0, i)
}
func TestContain(t *testing.T) {
assert := internal.NewAssert(t, "TestContain")