ru.hnau.jutils.collections.array.ByteArrayUtils.kt Maven / Gradle / Ivy
package ru.hnau.jutils.collections.array
inline fun ByteArray.findPos(predicate: (Byte) -> Boolean): Int? {
forEachIndexed { pos, element -> if (predicate.invoke(element)) return pos }
return null
}
inline fun ByteArray.convertFirstNotNull(converter: (Byte) -> R?): R? {
forEach { item ->
val convertionResult = converter.invoke(item)
if (convertionResult != null) {
return convertionResult
}
}
return null
}
fun ByteArray.circledGet(pos: Int): Byte {
val size = this.size
val normalizedPos = (pos % size).let { if (it < 0) it + size else it }
return get(normalizedPos)
}
//Для случая, когда список может быть пустым
fun ByteArray.circledGetOrNull(pos: Int) =
if (this.isEmpty()) null else circledGet(pos)
fun ByteArray.getOrFirst(pos: Int): Byte = getOrNull(pos) ?: get(0)
fun ByteArray.getOrFirstOrNull(pos: Int): Byte? =
if (this.isEmpty()) null else getOrNull(pos)
inline fun ByteArray.sumByByte(selector: (Byte) -> Byte): Byte {
var sum: Byte = 0
for (element in this) {
sum = (sum + selector.invoke(element)).toByte()
}
return sum
}
inline fun ByteArray.sumByShort(selector: (Byte) -> Short): Short {
var sum: Short = 0
for (element in this) {
sum = (sum + selector.invoke(element)).toShort()
}
return sum
}
inline fun ByteArray.sumByLong(selector: (Byte) -> Long): Long {
var sum: Long = 0
for (element in this) {
sum += selector.invoke(element)
}
return sum
}
inline fun ByteArray.sumByDouble(selector: (Byte) -> Double): Double {
var sum = 0.0
for (element in this) {
sum += selector.invoke(element)
}
return sum
}
inline fun ByteArray.sumByFloat(selector: (Byte) -> Float): Float {
var sum = 0f
for (element in this) {
sum += selector.invoke(element)
}
return sum
}
inline fun ByteArray.sumByString(selector: (Byte) -> String): String {
val result = StringBuilder()
for (element in this) {
result.append(selector.invoke(element))
}
return result.toString()
}