Refactor input processing

Fixed precision for calculated results
This commit is contained in:
Sad Ellie 2023-01-08 16:17:16 +04:00
parent 366cfb9768
commit 080ddbbd4c

View File

@ -47,6 +47,7 @@ import com.sadellie.unitto.data.OPERATORS
import com.sadellie.unitto.data.combine import com.sadellie.unitto.data.combine
import com.sadellie.unitto.data.preferences.UserPreferences import com.sadellie.unitto.data.preferences.UserPreferences
import com.sadellie.unitto.data.preferences.UserPreferencesRepository import com.sadellie.unitto.data.preferences.UserPreferencesRepository
import com.sadellie.unitto.data.setMinimumRequiredScale
import com.sadellie.unitto.data.toStringWith import com.sadellie.unitto.data.toStringWith
import com.sadellie.unitto.data.trimZeros import com.sadellie.unitto.data.trimZeros
import com.sadellie.unitto.data.units.AbstractUnit import com.sadellie.unitto.data.units.AbstractUnit
@ -59,6 +60,8 @@ import com.sadellie.unitto.data.units.database.MyBasedUnitsRepository
import com.sadellie.unitto.data.units.remote.CurrencyApi import com.sadellie.unitto.data.units.remote.CurrencyApi
import com.sadellie.unitto.data.units.remote.CurrencyUnitResponse import com.sadellie.unitto.data.units.remote.CurrencyUnitResponse
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import java.math.BigDecimal
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
@ -73,9 +76,6 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.math.BigDecimal
import java.math.RoundingMode
import javax.inject.Inject
@HiltViewModel @HiltViewModel
class MainViewModel @Inject constructor( class MainViewModel @Inject constructor(
@ -391,53 +391,41 @@ class MainViewModel @Inject constructor(
} }
private suspend fun convertInput() { private suspend fun convertInput() {
if (_unitFrom.value?.group == UnitGroup.NUMBER_BASE) { // Loading don't do anything
convertAsNumberBase() if ((_unitFrom.value == null) or (_unitTo.value == null)) return
} else {
convertAsExpression()
}
}
private suspend fun convertAsNumberBase() {
withContext(Dispatchers.Default) { withContext(Dispatchers.Default) {
while (isActive) { while (isActive) {
// Units are still loading, don't convert anything yet when (_unitFrom.value?.group) {
val unitFrom = _unitFrom.value ?: return@withContext UnitGroup.NUMBER_BASE -> convertAsNumberBase()
val unitTo = _unitTo.value ?: return@withContext else -> convertAsExpression()
}
cancel()
}
}
}
val conversionResult = try { private fun convertAsNumberBase() {
(unitFrom as NumberBaseUnit).convertToBase( val conversionResult: String = try {
(_unitFrom.value as NumberBaseUnit).convertToBase(
input = _input.value, input = _input.value,
toBase = (unitTo as NumberBaseUnit).base toBase = (_unitTo.value as NumberBaseUnit).base
) )
} catch (e: Exception) { } catch (e: Exception) {
when (e) { when (e) {
is ClassCastException -> { is ClassCastException -> return
cancel()
return@withContext
}
is NumberFormatException, is IllegalArgumentException -> "" is NumberFormatException, is IllegalArgumentException -> ""
else -> throw e else -> throw e
} }
} }
_result.update { conversionResult } _result.update { conversionResult }
cancel()
}
}
} }
private suspend fun convertAsExpression() { private fun convertAsExpression() {
withContext(Dispatchers.Default) {
while (isActive) {
// Units are still loading, don't convert anything yet
val unitFrom = _unitFrom.value ?: return@withContext
val unitTo = _unitTo.value ?: return@withContext
// First we clean the input from garbage at the end // First we clean the input from garbage at the end
var cleanInput = _input.value.dropLastWhile { !it.isDigit() } var cleanInput = _input.value.dropLastWhile { !it.isDigit() }
// Now we close open brackets that user didn't close // Now we close open brackets that user didn't close
// AUTOCLOSE ALL BRACKETS // AUTO-CLOSE ALL BRACKETS
val leftBrackets = _input.value.count { it.toString() == KEY_LEFT_BRACKET } val leftBrackets = _input.value.count { it.toString() == KEY_LEFT_BRACKET }
val rightBrackets = _input.value.count { it.toString() == KEY_RIGHT_BRACKET } val rightBrackets = _input.value.count { it.toString() == KEY_RIGHT_BRACKET }
val neededBrackets = leftBrackets - rightBrackets val neededBrackets = leftBrackets - rightBrackets
@ -446,52 +434,41 @@ class MainViewModel @Inject constructor(
// Now we evaluate expression in input // Now we evaluate expression in input
val evaluationResult: BigDecimal = try { val evaluationResult: BigDecimal = try {
Expressions().eval(cleanInput) Expressions().eval(cleanInput)
.setScale(_userPrefs.value.digitsPrecision, RoundingMode.HALF_EVEN)
.trimZeros()
} catch (e: Exception) { } catch (e: Exception) {
when (e) { when (e) {
is ExpressionException,
is ArrayIndexOutOfBoundsException, is ArrayIndexOutOfBoundsException,
is IndexOutOfBoundsException, is IndexOutOfBoundsException,
is NumberFormatException, is NumberFormatException,
is ArithmeticException -> { is ExpressionException,
// Invalid expression, can't do anything further is ArithmeticException -> return
cancel()
return@withContext
}
else -> throw e else -> throw e
} }
} }
// Evaluated. Hide calculated result if no expression entered.
// 123.456 will be true
// -123.456 will be true
// -123.456-123 will be false (first minus gets removed, ending with 123.456)
if (_input.value.removePrefix(KEY_MINUS).all { it.toString() !in OPERATORS }) {
// No operators
_calculated.update { null }
} else {
_calculated.update {
evaluationResult.toStringWith(
_userPrefs.value.outputFormat
)
}
}
// Now we just convert. // Now we just convert.
// We can use evaluation result here, input is valid // We can use evaluation result here, input is valid
val conversionResult: BigDecimal = unitFrom.convert( val conversionResult: BigDecimal = _unitFrom.value!!.convert(
unitTo, _unitTo.value!!,
evaluationResult, evaluationResult,
_userPrefs.value.digitsPrecision _userPrefs.value.digitsPrecision
) )
// Converted // Evaluated. Hide calculated result if no expression entered.
_result.update { conversionResult.toStringWith(_userPrefs.value.outputFormat) } // 123.456 will be true
// -123.456 will be true
// -123.456-123 will be false (first minus gets removed, ending with 123.456)
_calculated.update {
if (_input.value.removePrefix(KEY_MINUS).all { it.toString() !in OPERATORS }) {
null
} else {
evaluationResult
.setMinimumRequiredScale(_userPrefs.value.digitsPrecision)
.trimZeros()
.toStringWith(_userPrefs.value.outputFormat)
}
}
cancel() _result.update { conversionResult.toStringWith(_userPrefs.value.outputFormat) }
}
}
} }
private fun setInputSymbols(symbol: String, add: Boolean = true) { private fun setInputSymbols(symbol: String, add: Boolean = true) {