Skip to content

Commit

Permalink
Fix: Prevent consecutive operator input in CalculatorModal (#3359)
Browse files Browse the repository at this point in the history
* Fix: Prevent consecutive operator input in CalculatorModal

Resolved an issue in the CalculatorModal where consecutive operators could be added, resulting in invalid expressions.

- Updated the handleOperator function to ensure only one operator is added at a time.
- Replaced the last operator if a new operator is pressed.
- Ensured the input behaves like a standard calculator.

This change improves the user experience by preventing invalid expressions and aligning the calculator's behavior with user expectations.

* Fix: Ensure proper handling of consecutive operators in CalculatorModal

* Fix: Correct Detekt style issues in CalculatorModal.kt
  • Loading branch information
akashs056 committed Jul 22, 2024
1 parent 73c98fb commit 9e641eb
Showing 1 changed file with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,31 +117,31 @@ fun BoxWithConstraintsScope.CalculatorModal(
text = "÷",
testTag = "key_/"
) {
expression += "÷"
expression = handleOperator(expression, "÷")
}
},
FirstRowExtra = {
KeypadCircleButton(
text = "×",
testTag = "key_*"
) {
expression += "×"
expression = handleOperator(expression, "×")
}
},
SecondRowExtra = {
KeypadCircleButton(
text = "",
testTag = "key_-"
) {
expression += ""
expression = handleOperator(expression, "")
}
},
ThirdRowExtra = {
KeypadCircleButton(
text = "+",
testTag = "key_+"
) {
expression += "+"
expression = handleOperator(expression, "+")
}
},
FourthRowExtra = {
Expand Down Expand Up @@ -179,6 +179,19 @@ fun BoxWithConstraintsScope.CalculatorModal(
}
}

private fun handleOperator(expression: String, operator: String): String {
return if (expression.isNotEmpty() && expression.last().isOperator()) {
expression.dropLast(1) + operator
} else {
expression + operator
}
}

fun Char.isOperator(): Boolean = when (this) {
'+', '', '×', '÷' -> true
else -> false
}

private fun formatExpression(expression: String, currency: String): String {
var formattedExpression = expression

Expand Down

0 comments on commit 9e641eb

Please sign in to comment.