add joinTo

This commit is contained in:
InsanusMokrassar 2021-09-02 13:50:40 +06:00
parent 71f12f5f19
commit b70aa12be9
2 changed files with 37 additions and 0 deletions

View File

@ -2,6 +2,10 @@
## 0.5.23 ## 0.5.23
* `Versions`
* `Common`:
* New extensions `Iterable#joinTo` and `Array#joinTo`
## 0.5.22 ## 0.5.22
* `Versions` * `Versions`

View File

@ -0,0 +1,33 @@
package dev.inmo.micro_utils.common
inline fun <I, R> Iterable<I>.joinTo(
crossinline separatorFun: (I) -> R?,
prefix: R?,
postfix: R?,
crossinline transform: (I) -> R?
): List<R> {
val result = mutableListOf<R>()
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 <I, reified R> Array<I>.joinTo(
crossinline separatorFun: (I) -> R?,
prefix: R?,
postfix: R?,
crossinline transform: (I) -> R?
): Array<R> = asIterable().joinTo(separatorFun, prefix, postfix, transform).toTypedArray()