scoop:scoop.std:0.1.0
src/collections/slices.scoop
Selected production source · src/collections/slices.scoop
1
package scoop.collections3
internal fun requireCollectionCount(count: Long) {4
if (count < 0L) throw IllegalArgumentException(Some("negative count"))5
}7
/**8
* Copies at most the first nonnegative count of elements into a list.9
*/10
public fun <T> Iterable<T>.take(count: Long): List<T> {11
requireCollectionCount(count)12
if (count == 0L) return emptyList<T>()13
val result = ArrayList<T>()14
val source = iterator()15
var remaining = count16
while (remaining > 0L) {17
when (source.next()) {18
case None -> break19
case Some(val element) -> result.add(element)20
}21
remaining -= 1L22
}23
return ListSnapshot<T>(result.toArray())24
}26
/**27
* Skips the first nonnegative count and copies the remainder into a list.28
*/29
public fun <T> Iterable<T>.drop(count: Long): List<T> {30
requireCollectionCount(count)31
val result = ArrayList<T>()32
var remaining = count33
for (element in this) {34
if (remaining > 0L) remaining -= 1L else result.add(element)35
}36
return ListSnapshot<T>(result.toArray())37
}39
/**40
* Copies the longest initial run satisfying the predicate.41
*/42
public fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {43
val result = ArrayList<T>()44
for (element in this) {45
if (!predicate(element)) break46
result.add(element)47
}48
return ListSnapshot<T>(result.toArray())49
}51
/**52
* Skips the initial run satisfying the predicate and copies the remainder.53
*/54
public fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T> {55
val result = ArrayList<T>()56
var dropping = true57
for (element in this) {58
if (dropping) dropping = predicate(element)59
if (!dropping) result.add(element)60
}61
return ListSnapshot<T>(result.toArray())62
}64
/**65
* Returns an independent list in reverse iteration order.66
*/67
public fun <T> Iterable<T>.reversed(): List<T> {68
val result = toMutableList<T>()69
var left = 0L70
var right = result.size - 1L71
while (left < right) {72
val value = result[left]73
result[left] = result[right]74
result[right] = value75
left += 1L76
right -= 1L77
}78
return ListSnapshot<T>(result.toArray())79
}