Skip to main content

Calculator

Big O

HTML​

let displayValue = "0";
let firstOperand = null;
let operator = null;
let waitingForSecondOperand = false;

function inputDigit(digit) {
if (waitingForSecondOperand) {
displayValue = digit;
waitingForSecondOperand = false;
} else {
displayValue = displayValue === "0" ? digit : displayValue + digit;
}
updateDisplay();
}

function inputOperator(nextOperator) {
const inputValue = parseFloat(displayValue);

if (operator && waitingForSecondOperand) {
operator = nextOperator;
return;
}

if (firstOperand === null) {
firstOperand = inputValue;
} else if (operator) {
const result = performCalculation(firstOperand, inputValue, operator);
displayValue = `${parseFloat(result.toFixed(7))}`;
firstOperand = result;
}

operator = nextOperator;
waitingForSecondOperand = true;
updateDisplay();
}

function performCalculation(firstOperand, secondOperand, operator) {
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() {
if (operator === null || waitingForSecondOperand) return;
const secondOperand = parseFloat(displayValue);
displayValue = `${parseFloat(performCalculation(firstOperand, secondOperand, operator).toFixed(7))}`;
operator = null;
firstOperand = null;
waitingForSecondOperand = false;
updateDisplay();
}

function clearDisplay() {
displayValue = "0";
firstOperand = null;
operator = null;
waitingForSecondOperand = false;
updateDisplay();
}

function invertSign() {
displayValue = (parseFloat(displayValue) * -1).toString();
updateDisplay();
}

function updateDisplay() {
const display = document.querySelector("#display");
display.textContent = displayValue;
}

updateDisplay();