Skip to content

Commit 41c5a24

Browse files
committed
chore: improved readability of OTBranch.getPendingChanges()
1 parent 9736a70 commit 41c5a24

File tree

1 file changed

+14
-6
lines changed
  • model-datastructure/src/commonMain/kotlin/org/modelix/model/operations

1 file changed

+14
-6
lines changed

model-datastructure/src/commonMain/kotlin/org/modelix/model/operations/OTBranch.kt

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ class OTBranch(
3131
private val store: IDeserializingKeyValueStore,
3232
) : IBranch {
3333
private var currentOperations: MutableList<IAppliedOperation> = ArrayList()
34-
private val completedChanges: MutableList<Pair<List<IAppliedOperation>, ITree>> = ArrayList()
34+
private val completedChanges: MutableList<OpsAndTree> = ArrayList()
3535
private val id: String = branch.getId()
3636

3737
fun operationApplied(op: IAppliedOperation) {
@@ -52,10 +52,10 @@ class OTBranch(
5252
fun getPendingChanges(): Pair<List<IAppliedOperation>, ITree> {
5353
return runSynchronized(completedChanges) {
5454
val result = when (completedChanges.size) {
55-
0 -> emptyList<IAppliedOperation>() to computeReadT { it.tree }
56-
1 -> completedChanges[0]
57-
else -> completedChanges.flatMap { it.first } to completedChanges.last().second
58-
}
55+
0 -> OpsAndTree(computeReadT { it.tree })
56+
1 -> completedChanges.single()
57+
else -> completedChanges.last().merge(completedChanges.dropLast(1))
58+
}.asPair()
5959
completedChanges.clear()
6060
result
6161
}
@@ -91,7 +91,7 @@ class OTBranch(
9191
try {
9292
val result = computable()
9393
runSynchronized(completedChanges) {
94-
completedChanges += currentOperations to t.tree
94+
completedChanges += OpsAndTree(currentOperations, t.tree)
9595
}
9696
result
9797
} finally {
@@ -128,4 +128,12 @@ class OTBranch(
128128
}
129129

130130
protected fun checkNotEDT() {}
131+
132+
private class OpsAndTree(val ops: List<IAppliedOperation>, val tree: ITree) {
133+
constructor(tree: ITree) : this(emptyList(), tree)
134+
fun asPair(): Pair<List<IAppliedOperation>, ITree> = ops to tree
135+
fun merge(previous: List<OpsAndTree>): OpsAndTree {
136+
return OpsAndTree((previous + this).flatMap { it.ops }.toList(), tree)
137+
}
138+
}
131139
}

0 commit comments

Comments
 (0)