Scoop API

scoop:scoop.std:0.1.0

src/sequences/windows.scoop

Selected production source · src/sequences/windows.scoop

1package scoop.sequences
3import scoop.collections.ArrayDeque
4import scoop.collections.toList
6private class WindowingIterator<T>(
7 private val source: Iterator<T>, private val size: Long, private val step: Long, private val partial: Boolean
8) : Iterator<List<T>> {
9 private val window: ArrayDeque<T> = ArrayDeque<T>()
10 private var first: Boolean = true
11 private var ended: Boolean = false
13 private fun advance() {
14 var skip = step
15 while (skip > 0L && window.size > 0L) { window.removeFirst(); skip -= 1L }
16 while (skip > 0L && !ended) {
17 when (source.next()) {
18 case None -> ended = true
19 case Some(_) -> skip -= 1L
20 }
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 = true
29 case Some(val value) -> window.addLast(value)
30 }
31 }
32 if (window.size == 0L || (window.size < size && !partial)) return None
33 return Some(window.toList<T>())
34 }
37/**
38 * Evaluation is deferred until iteration. Produces copied windows at the requested step. Size and
39 * step must be positive; incomplete trailing windows are included only when partialWindows is
40 * true.
41 */
42public 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) }
47/**
48 * Evaluation is deferred until iteration. Partitions input into copied, nonoverlapping chunks of
49 * positive size; the final chunk may be shorter.
50 */
51public fun <T> Sequence<T>.chunked(size: Long): Sequence<List<T>> = windowed<T>(size, size, true)