Updated money config and add exception

This commit is contained in:
Sambo Chea 2020-08-26 20:19:06 +07:00
parent 9b7a215555
commit 226b97d7e9
2 changed files with 25 additions and 20 deletions

View File

@ -11,43 +11,45 @@ object MoneyConfig {
private const val SPLIT_ORD_2 = '=' 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 * Key is the currency
* Value is the rate * Value is the rate
*/ */
private val config = mutableMapOf<String, Double>() private val config: MutableMap<String, Double> = mutableMapOf()
fun parse(config: String): Map<String, Double> { /**
val result = mutableMapOf<String, Double>() * 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) val rates = config.split(SPLIT_ORD_1)
/**
* USD=1
* KHR=4000
* EUR=0.99
*
* USD -> currency
* 1 -> value
*/
rates.map { i -> rates.map { i ->
val temp = i.split(SPLIT_ORD_2) val temp = i.split(SPLIT_ORD_2)
if (temp.size == 2) { if (temp.size == 2) {
val currency = temp[0] val currency = temp[0].toUpperCase()
val value = temp[1].toDouble() 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 { } 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 // all currencies with its rate
fun getConfig() = this.config fun getConfig() = this.config
@Throws(MoneyCurrencyStateException::class)
fun getRate(currency: String): Double { 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!")
} }
} }

View File

@ -0,0 +1,3 @@
package com.cubetiqs.libra.moneyutils
class MoneyCurrencyStateException(message: String? = null) : IllegalStateException(message ?: "money currency not found!")