Szymon Jeziorski
10/26/2022, 10:05 AMfun <T> List<T>.cut(cutIndex: Int): Pair<List<T>, List<T>> {
if (cutIndex !in indices) throw IndexOutOfBoundsException("cutIndex $cutIndex out of bounds for List indices $indices")
return subList(0, cutIndex) to subList(cutIndex, size)
}
fun <T> List<T>.cutInHalf(): Pair<List<T>, List<T>> {
val midIndex = size / 2
return subList(0, midIndex) to subList(midIndex, size)
}
Having val sampleList = listOf(1, 8, 3, 9, 12, 4)
sampleList.cutInHalf()
would result in ([1, 8, 3], [9, 12, 4])
sampleList.cut(4)
would result in ([1, 8, 3, 9], [12, 4])
etc.
cutInHalf
wouldn't be ideal for Lists with odd number of elements, but I guess that should be obviousephemient
10/26/2022, 12:51 PMemptyList<Any>().cut(0)
will throw, but shouldn'tephemient
10/26/2022, 12:52 PMephemient
10/26/2022, 12:57 PM.slice()
instead of .subLst()
) but maybe you do want a view sometimesKlitos Kyriacou
10/26/2022, 1:45 PMfun <T> List<T>.splitAt(index: Int) = take(index) to drop(index)
is such a short definition that it's probably just as readable to use take(index) to drop(index)
every time instead of defining a separate function. (This creates new Lists, which you may or may not want.)