Created
January 4, 2017 20:47
-
-
Save fab1an/66baf6da26f8232b5b7e4da01306e062 to your computer and use it in GitHub Desktop.
ListEventCompressor
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
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