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

commonMain.kollections.ListUtils.kt Maven / Gradle / Ivy

There is a newer version: 3.0.11
Show newest version
package kollections

operator fun  List.plus(item: T): List = buildList {
    addAll(this@plus)
    add(item)
}

operator fun  List.plus(items: Iterable): List = buildList {
    addAll(this@plus)
    addAll(items)
}

operator fun  List.minus(item: T): List = buildList {
    [email protected] { if (it != item) add(it) }
}

operator fun  List.minus(items: Iterable): List = buildList {
    [email protected] { if (!items.contains(it)) add(it) }
}

fun  List.first(): T {
    if (size <= 0) throw NoSuchElementException("List is empty")
    return get(0)
}

fun  List.firstOrNull(): T? = if (size <= 0) null else get(0)
fun  List.last(): T {
    if (size <= 0) throw NoSuchElementException("List is empty")
    return get(size - 1)
}

fun  List.lastOrNull(): T? = if (size <= 0) null else get(size - 1)

val  List.indices get() = 0.. List.getOrNull(index: Int): T? = if (index >= size) null else get(index)

fun  List.mapIndexed(fn: (index: Int, item: T) -> R): List = buildList {
    var index = 0
    [email protected] { add(fn(index++, it)) }
}

/**
 * Returns a sublist from
 * @param start (inclusive) the beginning of the list
 * @param end (exclusive) the end of the sublist
 */
inline fun  List.subList(start: Int = 0, end: Int = size): List {
    if (end <= (start - 1)) return emptyList()
    val out = mutableListOf()
    val range = start..
        if (index in range) out.add(item)
    }
    return out
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy