Scoop API

scoop:scoop.std:0.1.0

src/collections/slices.scoop

Selected production source · src/collections/slices.scoop

1package scoop.collections
3internal 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 */
10public 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 = count
16 while (remaining > 0L) {
17 when (source.next()) {
18 case None -> break
19 case Some(val element) -> result.add(element)
20 }
21 remaining -= 1L
22 }
23 return ListSnapshot<T>(result.toArray())
26/**
27 * Skips the first nonnegative count and copies the remainder into a list.
28 */
29public fun <T> Iterable<T>.drop(count: Long): List<T> {
30 requireCollectionCount(count)
31 val result = ArrayList<T>()
32 var remaining = count
33 for (element in this) {
34 if (remaining > 0L) remaining -= 1L else result.add(element)
35 }
36 return ListSnapshot<T>(result.toArray())
39/**
40 * Copies the longest initial run satisfying the predicate.
41 */
42public fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {
43 val result = ArrayList<T>()
44 for (element in this) {
45 if (!predicate(element)) break
46 result.add(element)
47 }
48 return ListSnapshot<T>(result.toArray())
51/**
52 * Skips the initial run satisfying the predicate and copies the remainder.
53 */
54public fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T> {
55 val result = ArrayList<T>()
56 var dropping = true
57 for (element in this) {
58 if (dropping) dropping = predicate(element)
59 if (!dropping) result.add(element)
60 }
61 return ListSnapshot<T>(result.toArray())
64/**
65 * Returns an independent list in reverse iteration order.
66 */
67public fun <T> Iterable<T>.reversed(): List<T> {
68 val result = toMutableList<T>()
69 var left = 0L
70 var right = result.size - 1L
71 while (left < right) {
72 val value = result[left]
73 result[left] = result[right]
74 result[right] = value
75 left += 1L
76 right -= 1L
77 }
78 return ListSnapshot<T>(result.toArray())