All Downloads are FREE. Search and download functionalities are using the official Maven repository.

main.com.sceyt.chatuikit.extensions.CollectionExtensions.kt Maven / Gradle / Ivy

package com.sceyt.chatuikit.extensions

import androidx.core.util.Predicate

inline fun  Collection.findIndexed(predicate: (T) -> Boolean): Pair? {
    forEachIndexed { index: Int, item: T ->
        if (predicate(item)) {
            return Pair(index, item)
        }
    }
    return null
}

inline fun  ArrayList.findLastIndexed(predicate: (T) -> Boolean): Pair? {
    if (isEmpty()) return null
    for (i in indices.reversed()) {
        val item = get(i)
        if (predicate(item)) {
            return Pair(i, item)
        }
    }
    return null
}

fun  List.updateCommon(newList: List, predicate: (old: T, new: T) -> Boolean): List {
    val updateList = toMutableList()
    newList.forEach { newListElement ->
        findIndexed {
            predicate(it, newListElement)
        }?.let {
            updateList[it.first] = newListElement
        } ?: run { updateList.add(newListElement) }
    }
    return updateList
}

fun  MutableIterable.removeAllIf(predicate: Predicate): Boolean {
    val itr = iterator()
    var removed = false
    while (itr.hasNext()) {
        val t = itr.next()
        if (predicate.test(t)) {
            itr.remove()
            removed = true
        }
    }
    return removed
}

fun  HashMap.removeAllIf(predicate: Predicate): Boolean {
    var removed = false
    val iterator = entries.iterator()
    while (iterator.hasNext()) {
        val t = iterator.next()
        if (predicate.test(t.value)) {
            iterator.remove()
            removed = true
        }
    }
    return removed
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy