From 4b26a92b378025fb61758db9a4de8cbb2b67b9d1 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Fri, 5 May 2023 12:01:29 +0600 Subject: [PATCH] improve old diff API --- .../dev/inmo/micro_utils/common/DiffUtils.kt | 47 ++++++++++++------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/DiffUtils.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/DiffUtils.kt index 167c94a21fd..4f2f2635ac4 100644 --- a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/DiffUtils.kt +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/DiffUtils.kt @@ -200,20 +200,18 @@ inline fun Iterable.calculateStrictDiff( ) = calculateDiff(other, strictComparison = true) /** - * This method call [calculateDiff] with strict mode [strictComparison] and then apply differences to [this] - * mutable list + * Applies [diff] to [this] [MutableList] */ fun MutableList.applyDiff( - source: Iterable, - strictComparison: Boolean = false -): Diff = calculateDiff(source, strictComparison).also { - for (i in it.removed.indices.sortedDescending()) { - removeAt(it.removed[i].index) + diff: Diff +) { + for (i in diff.removed.indices.sortedDescending()) { + removeAt(diff.removed[i].index) } - it.added.forEach { (i, t) -> + diff.added.forEach { (i, t) -> add(i, t) } - it.replaced.forEach { (_, new) -> + diff.replaced.forEach { (_, new) -> set(new.index, new.value) } } @@ -222,17 +220,30 @@ fun MutableList.applyDiff( * This method call [calculateDiff] with strict mode [strictComparison] and then apply differences to [this] * mutable list */ +fun MutableList.applyDiff( + source: Iterable, + strictComparison: Boolean = false +): Diff = calculateDiff(source, strictComparison).also { + applyDiff(it) +} + +/** + * This method call [calculateDiff] and then apply differences to [this] + * mutable list + */ fun MutableList.applyDiff( source: Iterable, comparisonFun: (T?, T?) -> Boolean ): Diff = calculateDiff(source, comparisonFun).also { - for (i in it.removed.indices.sortedDescending()) { - removeAt(it.removed[i].index) - } - it.added.forEach { (i, t) -> - add(i, t) - } - it.replaced.forEach { (_, new) -> - set(new.index, new.value) - } + applyDiff(it) } + +/** + * Reverse [this] [Diff]. Result will contain [Diff.added] on [Diff.removed] (and vice-verse), all the + * [Diff.replaced] values will be reversed too + */ +fun Diff.reversed() = Diff( + removed = added, + replaced = replaced.map { it.second to it.first }, + added = removed +)