Scoop API

scoop:scoop.std:0.1.0

src/collections/windows.scoop

Selected production source · src/collections/windows.scoop

1package scoop.collections
3/**
4 * An element paired with its zero-based Long iteration index.
5 */
6public 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 */
11public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> = IndexedIterable<T>(this)
13private class IndexedIterable<T>(private val source: Iterable<T>) : Iterable<IndexedValue<T>> {
14 public override operator fun iterator(): Iterator<IndexedValue<T>> = IndexedIterator<T>(source.iterator())
17private class IndexedIterator<T>(private val source: Iterator<T>) : Iterator<IndexedValue<T>> {
18 private var index: Long = 0L
20 public override fun next(): IndexedValue<T>? = when (source.next()) {
21 case None -> None
22 case Some(val value) -> {
23 val result = IndexedValue<T>(index, value)
24 index = nextCollectionCount(index)
25 Some(result)
26 }
27 }
30/**
31 * Pairs elements by position, stopping when either input ends.
32 */
33public 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 -> break
41 case Some(val value) -> when (right.next()) {
42 case None -> break
43 case Some(val otherValue) -> result.add((value, otherValue))
44 }
45 }
46 }
47 return ListSnapshot<(T, R)>(result.toArray())
50/**
51 * Produces copied windows at the requested step. Size and step must be positive; incomplete
52 * trailing windows are included only when partialWindows is true.
53 */
54public 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 = false
60 while (true) {
61 while (!ended && window.size < size) {
62 when (source.next()) {
63 case None -> ended = true
64 case Some(val element) -> window.addLast(element)
65 }
66 }
67 if (window.isEmpty()) break
68 if (window.size < size && !partialWindows) break
69 result.add(window.toList())
70 var skip = step
71 while (skip > 0L && window.isNotEmpty()) { window.removeFirst(); skip -= 1L }
72 while (skip > 0L && !ended) {
73 when (source.next()) {
74 case None -> ended = true
75 case Some(_) -> skip -= 1L
76 }
77 }
78 }
79 return ListSnapshot<List<T>>(result.toArray())
82/**
83 * Partitions input into copied, nonoverlapping chunks of positive size; the final chunk may be
84 * shorter.
85 */
86public fun <T> Iterable<T>.chunked(size: Long): List<List<T>> = windowed<T>(size, size, true)