🏡 index : container_build.git


let operand;
let operation;
let displayString = '0';
let operationComplete = false;



function updateDisplay() {
  document.getElementById('display').value = displayString;
}

function addDigit(digit) {
  if (displayString === '0' || operationComplete) {
    displayString = digit;
  } else {
    displayString += digit;
  }

  operationComplete = false;
  updateDisplay();
}

function doAddition() {
  doOperation();
  operand = parseInt(displayString);
  displayString = '0';
  operation = '+';
}

function doSubtraction() {
  doOperation();
  operand = parseInt(displayString);
  displayString = '0';
  operation = '-';
}

function doMultiplication() {
  doOperation();
  operand = parseInt(displayString);
  displayString = '0';
  operation = '*';
}

function doDivision() {
  doOperation();
  operand = parseInt(displayString);
  displayString = '0';
  operation = '/';
}

function doClear() {
  operand = undefined;
  operation = undefined;
  displayString = '0';
  updateDisplay();
}

function doOperation() {
  if (operand === undefined || operation === undefined) {
    return;
  }

  let secondOperand = parseInt(displayString);
  if (operation === '+') {
    displayString = operand + secondOperand;
  } else if (operation === '-') {
    displayString = operand - secondOperand;
  } else if (operation === '*') {
    displayString = operand * secondOperand;
  } else if (operation === '/') {
    displayString = operand / secondOperand;
  }

  operationComplete = true;
}

function doEquals() {
  if (operand === undefined || operation === undefined) {
    return;
  }


  doOperation();

  operand = undefined;
  operation = undefined;
  updateDisplay();
}

function keyPress(event) {
  if (event.key >= '0' && event.key <= '9') {
    addDigit(event.key);
  } else if (event.key === '+') {
    doAddition();
  } else if (event.key === '-') {
    doSubtraction();
  } else if (event.key === '*') {
    doMultiplication();
  } else if (event.key === '/') {
    doDivision();
  } else if (event.key === 'Enter') {
    doEquals();
  } else if (event.key === 'c' || event.key === 'Escape') {
    doClear();
  }
}

document.addEventListener('keydown', keyPress);