commonMain.kollections.ListUtils.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kollections-primitive Show documentation
Show all versions of kollections-primitive Show documentation
A collection library that is built with interoperability in mind
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
}