package org.nstart.dep265.tletools.tools

import java.lang.NumberFormatException
import kotlin.math.min

fun <Double> MutableList<Double>.mapInPlace(transform: (Double) -> Double) {
    for (i in this.indices)
        this[i] = transform(this[i])
}

fun <Double> MutableList<Double>.mapInPlaceIndexed(transform: (Int, Double) -> Double) {
    for (i in this.indices)
        this[i] = transform(i, this[i])
}

fun String.leftJustified(size: Int, char: Char = ' ', truncate: Boolean = false): String {
    val padLen = size - length
    val builder = StringBuilder(this.padEnd(size, char))

    if (padLen <= 0 && truncate) {
            builder.replace(length + padLen, length, "")
    }

    return builder.toString()
}

fun String.rightJustified(size: Int, char: Char = ' ', truncate: Boolean = false): String {
    val padLen = size - length
    val builder = StringBuilder(this.padStart(size, char))

    if (padLen <= 0 && truncate) {
            builder.replace(length + padLen, length, "")
    }

    return builder.toString()
}

fun String.substringByLength(startIndex: Int, size: Int): String = this.substring(startIndex, min(startIndex + size, this.length))

operator fun <T, V: Enum<V>> Array<T>.get(index: Enum<V>): T = this[index.ordinal]
operator fun <T, V: Enum<V>> Array<T>.set(index: Enum<V>, value: T) {
    this[index.ordinal] = value
}

fun String?.isParsableToNum(): Boolean {

    if (this == null) return false

    try {
        this.toDouble()
    }
    catch (e: NumberFormatException) {
        return false
    }

    return true
}