demo-money-project/src/main/kotlin/com/example/demo/domain/MoneyDyn.kt

41 lines
1.2 KiB
Kotlin
Raw Normal View History

2020-08-26 18:08:09 +07:00
package com.example.demo.domain
2020-08-26 19:51:54 +07:00
class MoneyDyn(
2020-08-26 18:08:09 +07:00
var value: Double = 0.0,
var currency: String = "USD"
) {
2020-08-26 19:51:54 +07:00
fun addMoney(other: MoneyDyn): MoneyDyn {
this.value = this.value.plus(exchange(other, this.currency))
return this
}
fun exchange(fromMoney: MoneyDyn, exchangeCurrency: String): Double {
if (!fromMoney.currency.equals(exchangeCurrency, ignoreCase = true)) {
val rateFrom = MoneyConfig.getRate(fromMoney.currency)
val rateTo = MoneyConfig.getRate(exchangeCurrency)
return computeRate(amountFrom = fromMoney.value, rateFrom = rateFrom, rateTo = rateTo)
}
return fromMoney.value
2020-08-26 18:08:09 +07:00
}
2020-08-26 19:51:54 +07:00
fun exchangeTo(toCurrency: String): MoneyDyn {
return MoneyDyn(value = exchange(this, toCurrency))
2020-08-26 18:08:09 +07:00
}
2020-08-26 19:51:54 +07:00
private fun computeRate(
amountFrom: Double = 1.0,
baseRate: Double = 1.0,
rateFrom: Double,
rateTo: Double
): Double {
return amountFrom * ((baseRate / rateFrom) / (baseRate / rateTo))
}
private fun isEqualCurrency(other: MoneyDyn) =
this.currency.equals(other.currency, ignoreCase = true)
2020-08-26 18:08:09 +07:00
2020-08-26 19:51:54 +07:00
override fun toString(): String {
return "MoneyDyn(value=$value, currency='$currency')"
}
2020-08-26 18:08:09 +07:00
}