Skip to content

Commit 10a3fed

Browse files
committed
feat:slice LastIndexOf
1 parent f328c5e commit 10a3fed

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@ vendor/
1919

2020
# Go workspace file
2121
go.work
22+
.vscode/

slice/index.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,26 @@ func IndexOf[T comparable](array []T, value T, from int) int {
1919
}
2020
return -1
2121
}
22+
23+
// LastIndexOf
24+
// This method is like IndexOf except that it iterates over elements of array from right to left.
25+
func LastIndexOf[T comparable](array []T, value T, from int) int {
26+
var end int
27+
if from >= 0 {
28+
end = len(array) - 1 - from
29+
} else {
30+
end = -from - 1
31+
}
32+
if end < 0 {
33+
return -1
34+
}
35+
if end >= len(array) {
36+
end = len(array) - 1
37+
}
38+
for i := end; 0 <= end; i-- {
39+
if array[i] == value {
40+
return i
41+
}
42+
}
43+
return -1
44+
}

slice/index_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,14 @@ func ExampleIndexOf() {
1818
//5
1919
//1
2020
}
21+
22+
func ExampleLastIndexOf() {
23+
arr1 := []int{2, 3, 2, 3, 1}
24+
fmt.Println(LastIndexOf(arr1, 3, 0))
25+
fmt.Println(LastIndexOf(arr1, 3, 2))
26+
fmt.Println(LastIndexOf(arr1, 3, -3))
27+
//Output:
28+
//3
29+
//1
30+
//1
31+
}

0 commit comments

Comments
 (0)