Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Last active July 28, 2018 21:35
Show Gist options
  • Select an option

  • Save thomasnield/546f3ee12a17c2f6ce1f7ee4f2372cbf to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/546f3ee12a17c2f6ce1f7ee4f2372cbf to your computer and use it in GitHub Desktop.
Kotlin Collection Operator- Rolling Batches and Rolling Occurences
fun <T> List<T>.rollingBatches(batchSize: Int) = (0..size).asSequence().map { i ->
subList(i, (i + batchSize).let { if (it > size) size else it })
}.filter { it.size == batchSize }
enum class RecurrenceMode { PARTIAL_ONLY, FULL_ONLY, ALL }
fun <T> List<T>.rollingRecurrences(slotsNeeded: Int, gap: Int, recurrences: Int, mode: RecurrenceMode = RecurrenceMode.FULL_ONLY) =
(0..size).asSequence().map { i ->
(1..recurrences).asSequence().map { (it - 1) * gap }
.filter { it + i < size}
.map { r ->
subList(i + r, (i + r + slotsNeeded).let { if (it > size) size else it })
}
.toList()
}.filter {
when (mode) {
RecurrenceMode.ALL -> true
RecurrenceMode.FULL_ONLY -> it.size == recurrences && it.all { it.size == slotsNeeded }
RecurrenceMode.PARTIAL_ONLY -> it.size < recurrences || it.any { it.size < slotsNeeded }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment