diff --git a/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyConfig.kt b/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyConfig.kt index e58792e..c41a90b 100644 --- a/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyConfig.kt +++ b/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyConfig.kt @@ -11,43 +11,45 @@ object MoneyConfig { private const val SPLIT_ORD_2 = '=' /** + * All money currencies and its rate are stored in memory state for exchange or compute the value. + * * Key is the currency * Value is the rate */ - private val config = mutableMapOf() + private val config: MutableMap = mutableMapOf() - fun parse(config: String): Map { - val result = mutableMapOf() + /** + * Parse the config string to currency's map within rates + * Key is money's currency (String) + * Value is money's value (Double) + */ + fun parse(config: String, clearAllStates: Boolean = true) { + if (clearAllStates) { + this.config.clear() + } val rates = config.split(SPLIT_ORD_1) - /** - * USD=1 - * KHR=4000 - * EUR=0.99 - * - * USD -> currency - * 1 -> value - */ rates.map { i -> val temp = i.split(SPLIT_ORD_2) if (temp.size == 2) { - val currency = temp[0] + val currency = temp[0].toUpperCase() val value = temp[1].toDouble() - result.put(currency.toUpperCase(), value) + if (this.config.containsKey(currency)) { + this.config.replace(currency, value) + } else { + this.config.put(currency, value) + } } else { - throw IllegalArgumentException("invalid value!") + throw MoneyCurrencyStateException("money config format is not valid!") } } - - // if you want to use all set currencies without remove from memory, we should remove this line - this.config.clear() - this.config.putAll(result) - return result } // all currencies with its rate fun getConfig() = this.config + @Throws(MoneyCurrencyStateException::class) fun getRate(currency: String): Double { - return getConfig()[currency.toUpperCase()] ?: throw IllegalArgumentException("currency not found") + return getConfig()[currency.toUpperCase()] + ?: throw MoneyCurrencyStateException("money currency $currency is not valid!") } } \ No newline at end of file diff --git a/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyCurrencyStateException.kt b/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyCurrencyStateException.kt new file mode 100644 index 0000000..493cb0b --- /dev/null +++ b/src/main/kotlin/com/cubetiqs/libra/moneyutils/MoneyCurrencyStateException.kt @@ -0,0 +1,3 @@ +package com.cubetiqs.libra.moneyutils + +class MoneyCurrencyStateException(message: String? = null) : IllegalStateException(message ?: "money currency not found!") \ No newline at end of file