Created
May 31, 2022 09:34
-
-
Save andriesfc/57917aecf460c47c4428a9ddce2148fd to your computer and use it in GitHub Desktop.
Process list with merge function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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