From 3e0c908bbca9fc6aa1b121f983b8502a8077b9b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20MARRERO=20MEYER?= <143833750+timotheemm@users.noreply.github.com> Date: Fri, 26 Jan 2024 17:52:06 +0100 Subject: [PATCH] separate special case management into a separate function --- src/js/script.js | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/src/js/script.js b/src/js/script.js index d191685..27efbcd 100644 --- a/src/js/script.js +++ b/src/js/script.js @@ -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; } @@ -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 !== '.') { @@ -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 !== '.') { @@ -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.