Last active
February 16, 2023 21:37
-
-
Save sonique6784/6c6bb15306ad9d7248542b9b9465362a to your computer and use it in GitHub Desktop.
kotlin findLastIndex() extension function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/collections/Collections.kt | |
/** | |
* Returns the index of the last item in the list that match predicate | |
* @param predicate function returning boolean for matching element. | |
* | |
* @return the index of the last element found | |
* otherwise returns -1 | |
*/ | |
public inline fun <T> List<T>.findLastIndex(predicate: (T) -> Boolean): Int { | |
val iterator = this.listIterator(size) | |
var count = 1 | |
while (iterator.hasPrevious()) { | |
val element = iterator.previous() | |
if (predicate(element)) return size - count | |
count++ | |
} | |
return -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment