Skip to content

Instantly share code, notes, and snippets.

@fab1an
Created January 4, 2017 20:47
Show Gist options
  • Save fab1an/66baf6da26f8232b5b7e4da01306e062 to your computer and use it in GitHub Desktop.
Save fab1an/66baf6da26f8232b5b7e4da01306e062 to your computer and use it in GitHub Desktop.
ListEventCompressor
import ca.odell.glazedlists.event.ListEvent
import java.util.*
data class ChangeRange(val firstIndex: Int, var count: Int, val type: ChangeType) {
// ~ Delegated --------------------------------------------------------------------------------
val lastIndex: Int
get() = firstIndex + count - 1
// ~ Methods ----------------------------------------------------------------------------------
override fun toString(): String {
return "$type($firstIndex .. $lastIndex)"
}
// ~ Inner Types ------------------------------------------------------------------------------
enum class ChangeType {INSERT, UPDATE, DELETE }
}
fun ListEvent<*>.compress(): List<ChangeRange> {
val changes = LinkedList<ChangeRange>()
var batchedRange: ChangeRange? = null
while (nextBlock()) {
val count = blockEndIndex - blockStartIndex + 1
when (type) {
ListEvent.INSERT -> {
if (batchedRange == null) {
batchedRange = ChangeRange(blockStartIndex, count, type = INSERT)
} else if (batchedRange.type != INSERT || blockStartIndex != batchedRange.lastIndex + 1) {
changes += batchedRange
batchedRange = ChangeRange(blockStartIndex, count, type = INSERT)
} else {
batchedRange.count += count
}
}
ListEvent.UPDATE -> {
if (batchedRange == null) {
batchedRange = ChangeRange(blockStartIndex, count, type = UPDATE)
} else if (batchedRange.type != UPDATE || blockStartIndex != batchedRange.lastIndex + 1) {
changes += batchedRange
batchedRange = ChangeRange(blockStartIndex, count, type = UPDATE)
} else {
batchedRange.count += count
}
}
ListEvent.DELETE -> {
if (batchedRange == null) {
batchedRange = ChangeRange(blockStartIndex, count, type = DELETE)
} else if (batchedRange.type != DELETE || blockStartIndex != batchedRange.firstIndex) {
changes += batchedRange
batchedRange = ChangeRange(blockStartIndex, count, type = DELETE)
} else {
batchedRange.count += count
}
}
}
}
batchedRange?.let { changes += it }
return changes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment