Skip to content

Commit

Permalink
separate special case management into a separate function
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheeMM committed Jan 26, 2024
1 parent 9c28f63 commit 3e0c908
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions src/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@ let expression = '';
* @param {string} num - The number to append.
*/
function appendNumber(num) {
if (expression === 'NaN' || expression === 'Error' || expression === '-Infinity' || expression === 'Infinity') {
expression = '';
display.value = expression
}

handleSpecialCases();
expression += num;
display.value = expression;
}
Expand All @@ -20,11 +16,7 @@ function appendNumber(num) {
* @param {string} op - The operator to append.
*/
function appendOperator(op) {
if (expression === 'NaN' || expression === 'Error' || expression === '-Infinity' || expression === 'Infinity') {
expression = '';
display.value = expression
}

handleSpecialCases();
lastChar = expression.charAt(expression.length - 1);

if (lastChar !== '+' && lastChar !== '-' && lastChar !== '×' && lastChar !== '÷' && lastChar !== '.') {
Expand All @@ -37,11 +29,7 @@ function appendOperator(op) {
* Append a decimal point to the expression if the last character is not already a decimal point or an operator.
*/
function appendDecimal() {
if (expression === 'NaN' || expression === 'Error' || expression === '-Infinity' || expression === 'Infinity') {
expression = '';
display.value = expression
}

handleSpecialCases();
lastChar = expression.charAt(expression.length - 1);

if (lastChar !== '+' && lastChar !== '-' && lastChar !== '×' && lastChar !== '÷' && lastChar !== '.') {
Expand Down Expand Up @@ -87,6 +75,19 @@ function deleteLast() {
}
}

/**
* Handles special cases in the expression, clearing it if it matches predefined values.
* Special cases include 'NaN', 'Error', '-Infinity', and 'Infinity'.
*/
function handleSpecialCases() {
if (expression === 'NaN' || expression === 'Error' || expression === '-Infinity' || expression === 'Infinity') {
// Clear the expression and update the display
expression = '';
updateDisplay();
}
}


/**
* Evaluate the expression, replace '×' and '÷' with '*' and '/', and update the display.
* Handle errors and display 'Error' in case of an exception.
Expand Down

0 comments on commit 3e0c908

Please sign in to comment.