Use list iterators instead of indexed access in operations on lists taking a lambda.

Related to #KT-9607
This commit is contained in:
Ilya Gorbunov
2016-02-11 23:54:49 +03:00
parent b743e71cfc
commit f4f82656f7
5 changed files with 217 additions and 45 deletions
+65 -38
View File
@@ -278,10 +278,11 @@ public inline fun <T> Iterable<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
* Returns index of the first element matching the given [predicate], or -1 if the list does not contain such element. * Returns index of the first element matching the given [predicate], or -1 if the list does not contain such element.
*/ */
public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int { public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
for (index in indices) { var index = 0
if (predicate(this[index])) { for (item in this) {
if (predicate(item))
return index return index
} index++
} }
return -1 return -1
} }
@@ -304,9 +305,10 @@ public inline fun <T> Iterable<T>.indexOfLast(predicate: (T) -> Boolean): Int {
* Returns index of the last element matching the given [predicate], or -1 if the list does not contain such element. * Returns index of the last element matching the given [predicate], or -1 if the list does not contain such element.
*/ */
public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int { public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
for (index in indices.reversed()) { val iterator = this.listIterator(size)
if (predicate(this[index])) { while (iterator.hasPrevious()) {
return index if (predicate(iterator.previous())) {
return iterator.nextIndex()
} }
} }
return -1 return -1
@@ -365,8 +367,9 @@ public inline fun <T> Iterable<T>.last(predicate: (T) -> Boolean): T {
* @throws [NoSuchElementException] if no such element is found. * @throws [NoSuchElementException] if no such element is found.
*/ */
public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T { public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T {
for (index in this.indices.reversed()) { val iterator = this.listIterator(size)
val element = this[index] while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element if (predicate(element)) return element
} }
throw NoSuchElementException("List contains no element matching the predicate.") throw NoSuchElementException("List contains no element matching the predicate.")
@@ -438,8 +441,9 @@ public inline fun <T> Iterable<T>.lastOrNull(predicate: (T) -> Boolean): T? {
* Returns the last element matching the given [predicate], or `null` if no such element was found. * Returns the last element matching the given [predicate], or `null` if no such element was found.
*/ */
public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? { public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
for (index in this.indices.reversed()) { val iterator = this.listIterator(size)
val element = this[index] while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element if (predicate(element)) return element
} }
return null return null
@@ -546,8 +550,8 @@ public fun <T> Iterable<T>.drop(n: Int): List<T> {
return emptyList() return emptyList()
list = ArrayList<T>(resultSize) list = ArrayList<T>(resultSize)
if (this is List<T>) { if (this is List<T>) {
for (index in n..size - 1) { for (item in listIterator(n)) {
list.add(this[index]) list.add(item)
} }
return list return list
} }
@@ -574,9 +578,12 @@ public fun <T> List<T>.dropLast(n: Int): List<T> {
* Returns a list containing all elements except last elements that satisfy the given [predicate]. * Returns a list containing all elements except last elements that satisfy the given [predicate].
*/ */
public inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> { public inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> {
for (index in lastIndex downTo 0) { if (!isEmpty()) {
if (!predicate(this[index])) { val iterator = listIterator(size)
return take(index + 1) while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
return take(iterator.nextIndex() + 1)
}
} }
} }
return emptyList() return emptyList()
@@ -726,8 +733,13 @@ public fun <T> List<T>.takeLast(n: Int): List<T> {
val size = size val size = size
if (n >= size) return toList() if (n >= size) return toList()
val list = ArrayList<T>(n) val list = ArrayList<T>(n)
for (index in size - n .. size - 1) if (this is RandomAccess) {
list.add(this[index]) for (index in size - n .. size - 1)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list return list
} }
@@ -735,9 +747,18 @@ public fun <T> List<T>.takeLast(n: Int): List<T> {
* Returns a list containing last elements satisfying the given [predicate]. * Returns a list containing last elements satisfying the given [predicate].
*/ */
public inline fun <T> List<T>.takeLastWhile(predicate: (T) -> Boolean): List<T> { public inline fun <T> List<T>.takeLastWhile(predicate: (T) -> Boolean): List<T> {
for (index in lastIndex downTo 0) { if (isEmpty())
if (!predicate(this[index])) { return emptyList()
return drop(index + 1) val iterator = listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
iterator.next()
val expectedSize = size - iterator.nextIndex()
if (expectedSize == 0) return emptyList()
return ArrayList<T>(expectedSize).apply {
while (iterator.hasNext())
add(iterator.next())
}
} }
} }
return toList() return toList()
@@ -1368,10 +1389,12 @@ public inline fun <T, R> Iterable<T>.foldIndexed(initial: R, operation: (Int, R,
* Accumulates value starting with [initial] value and applying [operation] from right to left to each element and current accumulator value. * Accumulates value starting with [initial] value and applying [operation] from right to left to each element and current accumulator value.
*/ */
public inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, R) -> R): R { public inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, R) -> R): R {
var index = lastIndex
var accumulator = initial var accumulator = initial
while (index >= 0) { if (!isEmpty()) {
accumulator = operation(get(index--), accumulator) val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
} }
return accumulator return accumulator
} }
@@ -1383,11 +1406,13 @@ public inline fun <T, R> List<T>.foldRight(initial: R, operation: (T, R) -> R):
* and current accumulator value, and calculates the next accumulator value. * and current accumulator value, and calculates the next accumulator value.
*/ */
public inline fun <T, R> List<T>.foldRightIndexed(initial: R, operation: (Int, T, R) -> R): R { public inline fun <T, R> List<T>.foldRightIndexed(initial: R, operation: (Int, T, R) -> R): R {
var index = lastIndex
var accumulator = initial var accumulator = initial
while (index >= 0) { if (!isEmpty()) {
accumulator = operation(index, get(index), accumulator) val iterator = listIterator(size)
--index while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
} }
return accumulator return accumulator
} }
@@ -1554,11 +1579,12 @@ public inline fun <S, T: S> Iterable<T>.reduceIndexed(operation: (Int, S, T) ->
* Accumulates value starting with last element and applying [operation] from right to left to each element and current accumulator value. * Accumulates value starting with last element and applying [operation] from right to left to each element and current accumulator value.
*/ */
public inline fun <S, T: S> List<T>.reduceRight(operation: (T, S) -> S): S { public inline fun <S, T: S> List<T>.reduceRight(operation: (T, S) -> S): S {
var index = lastIndex val iterator = listIterator(size)
if (index < 0) throw UnsupportedOperationException("Empty list can't be reduced.") if (!iterator.hasPrevious())
var accumulator: S = get(index--) throw UnsupportedOperationException("Empty list can't be reduced.")
while (index >= 0) { var accumulator: S = iterator.previous()
accumulator = operation(get(index--), accumulator) while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
} }
return accumulator return accumulator
} }
@@ -1570,12 +1596,13 @@ public inline fun <S, T: S> List<T>.reduceRight(operation: (T, S) -> S): S {
* and current accumulator value, and calculates the next accumulator value. * and current accumulator value, and calculates the next accumulator value.
*/ */
public inline fun <S, T: S> List<T>.reduceRightIndexed(operation: (Int, T, S) -> S): S { public inline fun <S, T: S> List<T>.reduceRightIndexed(operation: (Int, T, S) -> S): S {
var index = lastIndex val iterator = listIterator(size)
if (index < 0) throw UnsupportedOperationException("Empty list can't be reduced.") if (!iterator.hasPrevious())
var accumulator: S = get(index--) throw UnsupportedOperationException("Empty list can't be reduced.")
while (index >= 0) { var accumulator: S = iterator.previous()
accumulator = operation(index, get(index), accumulator) while (iterator.hasPrevious()) {
--index val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
} }
return accumulator return accumulator
} }
@@ -54,6 +54,13 @@ class ListSpecificTest {
assertEquals(1, data.lastIndex) assertEquals(1, data.lastIndex)
} }
@Test
fun indexOfLast() {
expect(-1) { data.indexOfLast { it.contains("p") } }
expect(1) { data.indexOfLast { it.length == 3 } }
expect(-1) { empty.indexOfLast { it.startsWith('f') } }
}
@Test @Test
fun mutableList() { fun mutableList() {
val items = listOf("beverage", "location", "name") val items = listOf("beverage", "location", "name")
@@ -401,6 +401,19 @@ fun aggregates(): List<GenericFunction> {
return accumulator return accumulator
""" """
} }
body(Lists) {
"""
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
}
return accumulator
"""
}
} }
templates add f("fold(initial: R, operation: (R, T) -> R)") { templates add f("fold(initial: R, operation: (R, T) -> R)") {
@@ -436,6 +449,18 @@ fun aggregates(): List<GenericFunction> {
return accumulator return accumulator
""" """
} }
body(Lists) {
"""
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
}
return accumulator
"""
}
} }
templates add f("reduceIndexed(operation: (Int, T, T) -> T)") { templates add f("reduceIndexed(operation: (Int, T, T) -> T)") {
@@ -562,6 +587,21 @@ fun aggregates(): List<GenericFunction> {
--index --index
} }
return accumulator
"""
}
body(Lists) {
"""
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
val index = iterator.previousIndex()
accumulator = operation(index, iterator.previous(), accumulator)
}
return accumulator return accumulator
""" """
} }
@@ -660,6 +700,20 @@ fun aggregates(): List<GenericFunction> {
accumulator = operation(get(index--), accumulator) accumulator = operation(get(index--), accumulator)
} }
return accumulator
"""
}
body(Lists) {
"""
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator return accumulator
""" """
} }
@@ -130,6 +130,7 @@ fun elements(): List<GenericFunction> {
templates add f("indexOfFirst(predicate: (T) -> Boolean)") { templates add f("indexOfFirst(predicate: (T) -> Boolean)") {
inline(true) inline(true)
include(Lists)
doc { f -> "Returns index of the first ${f.element} matching the given [predicate], or -1 if the ${f.collection} does not contain such ${f.element}." } doc { f -> "Returns index of the first ${f.element} matching the given [predicate], or -1 if the ${f.collection} does not contain such ${f.element}." }
returns("Int") returns("Int")
body { body {
@@ -144,7 +145,7 @@ fun elements(): List<GenericFunction> {
""" """
} }
body(Lists, CharSequences, ArraysOfPrimitives, ArraysOfObjects) { body(CharSequences, ArraysOfPrimitives, ArraysOfObjects) {
""" """
for (index in indices) { for (index in indices) {
if (predicate(this[index])) { if (predicate(this[index])) {
@@ -174,7 +175,7 @@ fun elements(): List<GenericFunction> {
""" """
} }
body(Lists, CharSequences, ArraysOfPrimitives, ArraysOfObjects) { body(CharSequences, ArraysOfPrimitives, ArraysOfObjects) {
""" """
for (index in indices.reversed()) { for (index in indices.reversed()) {
if (predicate(this[index])) { if (predicate(this[index])) {
@@ -184,6 +185,17 @@ fun elements(): List<GenericFunction> {
return -1 return -1
""" """
} }
body(Lists) {
"""
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (predicate(iterator.previous())) {
return iterator.nextIndex()
}
}
return -1
"""
}
} }
templates add f("elementAt(index: Int)") { templates add f("elementAt(index: Int)") {
@@ -535,7 +547,7 @@ fun elements(): List<GenericFunction> {
""" """
} }
body(CharSequences, ArraysOfPrimitives, ArraysOfObjects, Lists) { f -> body(CharSequences, ArraysOfPrimitives, ArraysOfObjects) { f ->
""" """
for (index in this.indices.reversed()) { for (index in this.indices.reversed()) {
val element = this[index] val element = this[index]
@@ -544,6 +556,16 @@ fun elements(): List<GenericFunction> {
throw NoSuchElementException("${f.doc.collection.capitalize()} contains no ${f.doc.element} matching the predicate.") throw NoSuchElementException("${f.doc.collection.capitalize()} contains no ${f.doc.element} matching the predicate.")
""" """
} }
body(Lists) { f ->
"""
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
throw NoSuchElementException("${f.doc.collection.capitalize()} contains no ${f.doc.element} matching the predicate.")
"""
}
} }
templates add f("lastOrNull(predicate: (T) -> Boolean)") { templates add f("lastOrNull(predicate: (T) -> Boolean)") {
@@ -569,7 +591,7 @@ fun elements(): List<GenericFunction> {
""" """
} }
body(CharSequences, ArraysOfPrimitives, ArraysOfObjects, Lists) { body(CharSequences, ArraysOfPrimitives, ArraysOfObjects) {
""" """
for (index in this.indices.reversed()) { for (index in this.indices.reversed()) {
val element = this[index] val element = this[index]
@@ -578,6 +600,17 @@ fun elements(): List<GenericFunction> {
return null return null
""" """
} }
body(Lists) {
"""
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
return null
"""
}
} }
templates add f("findLast(predicate: (T) -> Boolean)") { templates add f("findLast(predicate: (T) -> Boolean)") {
@@ -49,8 +49,8 @@ fun filtering(): List<GenericFunction> {
list = ArrayList<T>(resultSize) list = ArrayList<T>(resultSize)
if (this is List<T>) { if (this is List<T>) {
for (index in n..size - 1) { for (item in listIterator(n)) {
list.add(this[index]) list.add(item)
} }
return list return list
} }
@@ -202,7 +202,7 @@ fun filtering(): List<GenericFunction> {
""" """
} }
body(Lists, ArraysOfObjects, ArraysOfPrimitives) { body(ArraysOfObjects, ArraysOfPrimitives) {
""" """
require(n >= 0) { "Requested element count $n is less than zero." } require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList() if (n == 0) return emptyList()
@@ -214,6 +214,23 @@ fun filtering(): List<GenericFunction> {
return list return list
""" """
} }
body(Lists) {
"""
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
val size = size
if (n >= size) return toList()
val list = ArrayList<T>(n)
if (this is RandomAccess) {
for (index in size - n .. size - 1)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list
"""
}
} }
templates add f("dropWhile(predicate: (T) -> Boolean)") { templates add f("dropWhile(predicate: (T) -> Boolean)") {
@@ -316,6 +333,19 @@ fun filtering(): List<GenericFunction> {
return emptyList() return emptyList()
""" """
} }
body(Lists) {
"""
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
return take(iterator.nextIndex() + 1)
}
}
}
return emptyList()
"""
}
doc(Strings) { "Returns a string containing all characters except last characters that satisfy the given [predicate]." } doc(Strings) { "Returns a string containing all characters except last characters that satisfy the given [predicate]." }
doc(CharSequences) { "Returns a subsequence of this char sequence containing all characters except last characters that satisfy the given [predicate]." } doc(CharSequences) { "Returns a subsequence of this char sequence containing all characters except last characters that satisfy the given [predicate]." }
@@ -347,6 +377,27 @@ fun filtering(): List<GenericFunction> {
return toList() return toList()
""" """
} }
body(Lists) {
"""
if (isEmpty())
return emptyList()
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
iterator.next()
val expectedSize = size - iterator.nextIndex()
if (expectedSize == 0) return emptyList()
return ArrayList<T>(expectedSize).apply {
while (iterator.hasNext())
add(iterator.next())
}
}
}
return toList()
"""
// TODO: Use iterator.toList() internal method in 1.1
// return iterator.toList(size - iterator.nextIndex())
}
doc(Strings) { "Returns a string containing last characters that satisfy the given [predicate]." } doc(Strings) { "Returns a string containing last characters that satisfy the given [predicate]." }
doc(CharSequences) { "Returns a subsequence of this char sequence containing last characters that satisfy the given [predicate]." } doc(CharSequences) { "Returns a subsequence of this char sequence containing last characters that satisfy the given [predicate]." }