scoop:scoop.std:0.1.0
src/sequences/windows.scoop
Selected production source · src/sequences/windows.scoop
1
package scoop.sequences3
import scoop.collections.ArrayDeque4
import scoop.collections.toList6
private class WindowingIterator<T>(7
private val source: Iterator<T>, private val size: Long, private val step: Long, private val partial: Boolean8
) : Iterator<List<T>> {9
private val window: ArrayDeque<T> = ArrayDeque<T>()10
private var first: Boolean = true11
private var ended: Boolean = false13
private fun advance() {14
var skip = step15
while (skip > 0L && window.size > 0L) { window.removeFirst(); skip -= 1L }16
while (skip > 0L && !ended) {17
when (source.next()) {18
case None -> ended = true19
case Some(_) -> skip -= 1L20
}21
}22
}24
public override fun next(): List<T>? {25
if (first) first = false else advance()26
while (!ended && window.size < size) {27
when (source.next()) {28
case None -> ended = true29
case Some(val value) -> window.addLast(value)30
}31
}32
if (window.size == 0L || (window.size < size && !partial)) return None33
return Some(window.toList<T>())34
}35
}37
/**38
* Evaluation is deferred until iteration. Produces copied windows at the requested step. Size and39
* step must be positive; incomplete trailing windows are included only when partialWindows is40
* true.41
*/42
public fun <T> Sequence<T>.windowed(size: Long, step: Long = 1L, partialWindows: Boolean = false): Sequence<List<T>> {43
if (size <= 0L || step <= 0L) throw IllegalArgumentException(Some("non-positive window size or step"))44
return FactorySequence<List<T>> { WindowingIterator<T>(iterator(), size, step, partialWindows) }45
}47
/**48
* Evaluation is deferred until iteration. Partitions input into copied, nonoverlapping chunks of49
* positive size; the final chunk may be shorter.50
*/51
public fun <T> Sequence<T>.chunked(size: Long): Sequence<List<T>> = windowed<T>(size, size, true)