30 lines
1.0 KiB
Kotlin
30 lines
1.0 KiB
Kotlin
package moe.kageru.sekwences
|
|
|
|
/**
|
|
* Returns a sequences that optionally merges adjacent elements.
|
|
* Heavily inspired by Itertools.coalesce() from the Rust crate.
|
|
*
|
|
* The merge function will be passed two adjacent elements in the sequence.
|
|
* If the two can be merged, the result of the merging process should be returned.
|
|
* If null is returned, the first of the two elements is returned,
|
|
* and the second will be used as the first element in the next merge operation.
|
|
*
|
|
* https://docs.rs/itertools/0.8.0/itertools/trait.Itertools.html#method.coalesce
|
|
*/
|
|
fun <T> Sequence<T>.coalesce(merger: (T, T) -> T?): Sequence<T> {
|
|
return if (this.iterator().hasNext()) {
|
|
CoalescingSequence(this, merger)
|
|
} else {
|
|
emptySequence()
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Modifies the current [Sequence] by adding a peek() method
|
|
* that returns the next element or null without advancing the sequence.
|
|
* Calling peek() multiple times without next() will return the same value.
|
|
*/
|
|
fun <T> Sequence<T>.peekable(): PeekableSequence<T> {
|
|
return PeekableSequence(this)
|
|
}
|