Skip to content

Instantly share code, notes, and snippets.

@andriesfc
Created May 31, 2022 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriesfc/57917aecf460c47c4428a9ddce2148fd to your computer and use it in GitHub Desktop.
Save andriesfc/57917aecf460c47c4428a9ddce2148fd to your computer and use it in GitHub Desktop.
Process list with merge function
fun <T> MutableList<T>.processWindowWith(
withinWindow: (List<T>, T) -> Boolean,
process: (MutableList<T>) -> Unit,
): MutableList<T> {
if (isEmpty()) {
return this
}
var lastWindowMerged: MutableList<T>? = null
val merged = fold(mutableListOf<MutableList<T>>()) { acc, record ->
val last = acc.lastOrNull()
if (last == null) {
acc += mutableListOf(record)
} else if (withinWindow(last, record)) {
last += record
} else {
process(last)
lastWindowMerged = last
acc += mutableListOf(record)
}
acc
}
if (lastWindowMerged != merged.last()) {
process(merged.last())
}
clear()
addAll(merged.flatten())
return this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment