let displayValue: string = "0";
let firstOperand: number | null = null;
let operator: string | null = null;
let waitingForSecondOperand: boolean = false;
function inputDigit(digit: string): void {
if (waitingForSecondOperand) {
displayValue = digit;
waitingForSecondOperand = false;
} else {
displayValue = displayValue === "0" ? digit : displayValue + digit;
}
updateDisplay();
}
function inputOperator(nextOperator: string): void {
const inputValue: number = parseFloat(displayValue);
if (operator && waitingForSecondOperand) {
operator = nextOperator;
return;
}
if (firstOperand === null) {
firstOperand = inputValue;
} else if (operator) {
const result: number = performCalculation(
firstOperand,
inputValue,
operator,
);
displayValue = `${parseFloat(result.toFixed(7))}`;
firstOperand = result;
}
operator = nextOperator;
waitingForSecondOperand = true;
updateDisplay();
}
function performCalculation(
firstOperand: number,
secondOperand: number,
operator: string,
): number {
switch (operator) {
case "+":
return firstOperand + secondOperand;
case "-":
return firstOperand - secondOperand;
case "*":
return firstOperand * secondOperand;
case "/":
if (secondOperand === 0) {
alert("Cannot divide by zero");
return firstOperand;
}
return firstOperand / secondOperand;
case "%":
return firstOperand % secondOperand;
default:
return secondOperand;
}
}
function calculateResult(): void {
if (operator === null || waitingForSecondOperand) return;
const secondOperand: number = parseFloat(displayValue);
displayValue = `${parseFloat(performCalculation(firstOperand!, secondOperand, operator).toFixed(7))}`;
operator = null;
firstOperand = null;
waitingForSecondOperand = false;
updateDisplay();
}
function clearDisplay(): void {
displayValue = "0";
firstOperand = null;
operator = null;
waitingForSecondOperand = false;
updateDisplay();
}
function invertSign(): void {
displayValue = (parseFloat(displayValue) * -1).toString();
updateDisplay();
}
function updateDisplay(): void {
const display: HTMLElement | null = document.querySelector("#display");
if (display) {
display.textContent = displayValue;
}
}
updateDisplay();