From b70aa12be9965f38392889cbcff4b4bd0797b243 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Thu, 2 Sep 2021 13:50:40 +0600 Subject: [PATCH] add joinTo --- CHANGELOG.md | 4 +++ .../dev/inmo/micro_utils/common/JoinTo.kt | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 common/src/commonMain/kotlin/dev/inmo/micro_utils/common/JoinTo.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b91344fcc0..344166d8225 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## 0.5.23 +* `Versions` +* `Common`: + * New extensions `Iterable#joinTo` and `Array#joinTo` + ## 0.5.22 * `Versions` diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/JoinTo.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/JoinTo.kt new file mode 100644 index 00000000000..553c4f77783 --- /dev/null +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/JoinTo.kt @@ -0,0 +1,33 @@ +package dev.inmo.micro_utils.common + +inline fun Iterable.joinTo( + crossinline separatorFun: (I) -> R?, + prefix: R?, + postfix: R?, + crossinline transform: (I) -> R? +): List { + val result = mutableListOf() + val iterator = iterator() + + prefix ?.let(result::add) + + while (iterator.hasNext()) { + val element = iterator.next() + result.add(transform(element) ?: continue) + + if (iterator.hasNext()) { + result.add(separatorFun(element) ?: continue) + } + } + + postfix ?.let(result::add) + + return result +} + +inline fun Array.joinTo( + crossinline separatorFun: (I) -> R?, + prefix: R?, + postfix: R?, + crossinline transform: (I) -> R? +): Array = asIterable().joinTo(separatorFun, prefix, postfix, transform).toTypedArray()