Last active
July 28, 2018 21:35
-
-
Save thomasnield/546f3ee12a17c2f6ce1f7ee4f2372cbf to your computer and use it in GitHub Desktop.
Kotlin Collection Operator- Rolling Batches and Rolling Occurences
This file contains hidden or 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> 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