v2 / vlib / arrays / index_of.v
26 lines · 24 sloc · 979 bytes · 33602047bc39ebb6bde139036a76073c1c10959d
Raw
1module arrays
2
3// index_of_first returns the index of the first element of `array`, for which the predicate fn returns true.
4// If predicate does not return true for any of the elements, then index_of_first will return -1.
5// Example: assert arrays.index_of_first([4,5,0,7,0,9], fn(idx int, x int) bool { return x == 0 }) == 2
6pub fn index_of_first[T](array []T, predicate fn (idx int, elem T) bool) int {
7 for i, e in array {
8 if predicate(i, e) {
9 return i
10 }
11 }
12 return -1
13}
14
15// index_of_last returns the index of the last element of `array`, for which the predicate fn returns true.
16// If predicate does not return true for any of the elements, then index_of_last will return -1.
17// Example: assert arrays.index_of_last([4,5,0,7,0,9], fn(idx int, x int) bool { return x == 0 }) == 4
18pub fn index_of_last[T](array []T, predicate fn (idx int, elem T) bool) int {
19 for i := array.len - 1; i >= 0; i-- {
20 e := array[i]
21 if predicate(i, e) {
22 return i
23 }
24 }
25 return -1
26}
27