Skip to content

Instantly share code, notes, and snippets.

@guissalustiano
Last active January 8, 2024 16:01
Show Gist options
  • Save guissalustiano/8d6516226474a15166b6e1c0b3258a96 to your computer and use it in GitHub Desktop.
Save guissalustiano/8d6516226474a15166b6e1c0b3258a96 to your computer and use it in GitHub Desktop.
Naive `Iterable<T>.chunkedBy` implemention to Kotlin
inline fun <T> Iterable<T>.chunkedBy(
predicate: (T) -> Boolean
): List<List<T>> {
val iterator = this.iterator()
if (!iterator.hasNext()) {
return emptyList()
}
var lastElem = iterator.next()
var lastList = mutableListOf(lastElem)
val acc = mutableListOf<MutableList<T>>(lastList)
for(elem in iterator) {
if (predicate(lastElem) == predicate(elem)) {
lastList.add(elem)
} else {
lastList = mutableListOf(elem)
acc.add(lastList)
}
lastElem = elem
}
return acc.map{it.toList()}.toList()
}
fun main() {
val a = listOf(1, 2, 2, 3, 3, 5, 5, 6)
print(a.chunkedBy{it % 2 == 0})
// [[1], [2, 2], [3, 3, 5, 5], [6]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment