scoop:scoop.std:0.1.0
src/collections/windows.scoop
Selected production source · src/collections/windows.scoop
1
package scoop.collections3
/**4
* An element paired with its zero-based Long iteration index.5
*/6
public struct IndexedValue<T>(val index: Long, val value: T)8
/**9
* Pairs each element with its zero-based Long index as it is iterated.10
*/11
public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> = IndexedIterable<T>(this)13
private class IndexedIterable<T>(private val source: Iterable<T>) : Iterable<IndexedValue<T>> {14
public override operator fun iterator(): Iterator<IndexedValue<T>> = IndexedIterator<T>(source.iterator())15
}17
private class IndexedIterator<T>(private val source: Iterator<T>) : Iterator<IndexedValue<T>> {18
private var index: Long = 0L20
public override fun next(): IndexedValue<T>? = when (source.next()) {21
case None -> None22
case Some(val value) -> {23
val result = IndexedValue<T>(index, value)24
index = nextCollectionCount(index)25
Some(result)26
}27
}28
}30
/**31
* Pairs elements by position, stopping when either input ends.32
*/33
public fun <T, R> Iterable<T>.zip(other: Iterable<R>): List<(T, R)> {34
val result = ArrayList<(T, R)>()35
val left = iterator()36
val right = other.iterator()37
while (true) {38
val first = left.next()39
when (first) {40
case None -> break41
case Some(val value) -> when (right.next()) {42
case None -> break43
case Some(val otherValue) -> result.add((value, otherValue))44
}45
}46
}47
return ListSnapshot<(T, R)>(result.toArray())48
}50
/**51
* Produces copied windows at the requested step. Size and step must be positive; incomplete52
* trailing windows are included only when partialWindows is true.53
*/54
public fun <T> Iterable<T>.windowed(size: Long, step: Long = 1L, partialWindows: Boolean = false): List<List<T>> {55
if (size <= 0L || step <= 0L) throw IllegalArgumentException(Some("non-positive window size or step"))56
val result = ArrayList<List<T>>()57
val window = ArrayDeque<T>()58
val source = iterator()59
var ended = false60
while (true) {61
while (!ended && window.size < size) {62
when (source.next()) {63
case None -> ended = true64
case Some(val element) -> window.addLast(element)65
}66
}67
if (window.isEmpty()) break68
if (window.size < size && !partialWindows) break69
result.add(window.toList())70
var skip = step71
while (skip > 0L && window.isNotEmpty()) { window.removeFirst(); skip -= 1L }72
while (skip > 0L && !ended) {73
when (source.next()) {74
case None -> ended = true75
case Some(_) -> skip -= 1L76
}77
}78
}79
return ListSnapshot<List<T>>(result.toArray())80
}82
/**83
* Partitions input into copied, nonoverlapping chunks of positive size; the final chunk may be84
* shorter.85
*/86
public fun <T> Iterable<T>.chunked(size: Long): List<List<T>> = windowed<T>(size, size, true)