From 2f70a1cfb455276a88b31a1d86bd4870086e2e8e Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Tue, 1 Oct 2024 20:30:45 +0600 Subject: [PATCH] solution of #489 --- CHANGELOG.md | 2 ++ .../inmo/micro_utils/common/WithReplaced.kt | 5 +++++ .../micro_utils/common/WithReplacedTest.kt | 21 +++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 common/src/commonMain/kotlin/dev/inmo/micro_utils/common/WithReplaced.kt create mode 100644 common/src/commonTest/kotlin/dev/inmo/micro_utils/common/WithReplacedTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 72c30759b00..a09fb554e17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 0.22.5 +* `Common`: + * Add extension `withReplacedAt`/`withReplaced` ([#489](https://github.com/InsanusMokrassar/MicroUtils/issues/489)) * `Coroutines`: * Add extension `Flow.debouncedBy` diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/WithReplaced.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/WithReplaced.kt new file mode 100644 index 00000000000..2fa36eaf05d --- /dev/null +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/WithReplaced.kt @@ -0,0 +1,5 @@ +package dev.inmo.micro_utils.common + +fun Iterable.withReplacedAt(i: Int, block: (T) -> T): List = take(i) + block(elementAt(i)) + drop(i + 1) +fun Iterable.withReplaced(t: T, block: (T) -> T): List = withReplacedAt(indexOf(t), block) + diff --git a/common/src/commonTest/kotlin/dev/inmo/micro_utils/common/WithReplacedTest.kt b/common/src/commonTest/kotlin/dev/inmo/micro_utils/common/WithReplacedTest.kt new file mode 100644 index 00000000000..14a410e2af5 --- /dev/null +++ b/common/src/commonTest/kotlin/dev/inmo/micro_utils/common/WithReplacedTest.kt @@ -0,0 +1,21 @@ +package dev.inmo.micro_utils.common + +import kotlin.test.Test +import kotlin.test.assertEquals + +class WithReplacedTest { + @Test + fun testReplaced() { + val data = 0 until 10 + val testData = Int.MAX_VALUE + + for (i in 0 until data.last) { + val withReplaced = data.withReplacedAt(i) { + testData + } + val dataAsMutableList = data.toMutableList() + dataAsMutableList[i] = testData + assertEquals(withReplaced, dataAsMutableList.toList()) + } + } +} \ No newline at end of file