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