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

tech.sirwellington.alchemy.kotlin.extensions.ListsPlus.kt Maven / Gradle / Ivy

/*
 * Copyright 2017 SirWellington Tech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package tech.sirwellington.alchemy.kotlin.extensions

import java.util.Collections


/**
 *
 * @author SirWellington
 */

/**
 * Checks whether [index] is a valid index in `this` [List].
 *
 * @return `true` if [index] is a valid index in `this`, `false` otherwise.
 */
fun  List.isValidIndex(index: Int): Boolean
{
    if (index < 0) return false

    return index < size
}

/**
 * Checks to make sure [index] is not a valid index in this [List].
 *
 * @return `true` if [index] is an invalid index in `this`, `false` if it a valid index.
 */
fun  List.notValidIndex(index: Int) = !isValidIndex(index)

/**
 * @return `true` if `this` [Int] is a valid index in [list], false if it is not.
 */
fun  Int.isValidIndexIn(list: List): Boolean
{
    if (this < 0) return false

    return this < list.size
}

/**
 * @return true if this [Number][Int] is a valid index in the given [List],
 * false otherwise.
 */
fun  Int.notValidIndexIn(list: List) = !isValidIndexIn(list)

/**
 * @return A shuffled version of this [List].
 */
fun  List.shuffled(): List
{
    val result = this.toMutableList()
    Collections.shuffle(result)
    return result
}

/**
 *
 * @return a random element from the list, null if the list is empty or null.
 */
val  List?.anyElement: T?
    get()
    {
        if (this == null) return null

        val index = (0..size).random()

        return if (index.isValidIndexIn(this)) this[index] else null
    }

/**
 * Removes all elements from the collection that match the given predicate.
 */
fun  MutableCollection.removeElementIf(predicate: (T) -> (Boolean))
{
    val elementsToRemove = this.filter(predicate).toList()
    this.removeAll(elementsToRemove)
}

/**
 * Adds an element to be front of a [List].
 */
inline fun  MutableList.addToFront(element: T)
{
    add(0, element)
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy