Skip to content

Instantly share code, notes, and snippets.

@joshfreemanIO
Last active August 29, 2015 14:13
Show Gist options
  • Save joshfreemanIO/eaca112f8a19fc950e87 to your computer and use it in GitHub Desktop.
Save joshfreemanIO/eaca112f8a19fc950e87 to your computer and use it in GitHub Desktop.
Calculator demo
var buttons = document.getElementsByTagName('button');
var display = document.getElementById('display');
var currentValue = 0;
var operand = 0;
var operator = '=';
var previousClicked = '=';
var cleared = true;
/**
* Given a button value, preform the correct operation and update the display
*/
var pressButton = function () {
buttonValue = this.value;
if (buttonValue.match(/\d/)) {
pressNumber(buttonValue);
} else if (buttonValue === '=') {
pressEquals();
} else if (buttonValue === 'C') {
pressClear(buttonValue);
} else {
pressOperator(buttonValue);
}
console.log('current operator: ', operator)
console.log('current opeand: ', operand)
console.log('current value: ', currentValue)
previousClicked = buttonValue;
return currentValue;
}
/**
* Reset the calculator
*/
var pressClear = function () {
resetOperand();
currentValue = 0;
operator = '=';
updateDisplay(currentValue);
}
/**
* Press =
* Simply calls the last action with previous values
*/
var pressEquals = function () {
currentValue = calculate(currentValue, operand, operator);
updateDisplay(currentValue);
}
/**
* Press + - * /
*
* Sets the new operation
*
* If the last button clicked was not =, calculate a new value
*
* Reset the operand
*/
var pressOperator = function (buttonValue) {
operator = buttonValue;
if (previousClicked !== '=') {
currentValue = calculate(currentValue, operand, operator);
}
updateDisplay(currentValue);
resetOperand();
}
/**
* Press a number
*
* Stores the current state of numbers pressed
*/
var pressNumber = function (buttonValue) {
operand = operand.toString() + buttonValue;
operand = parseInt(operand);
if (previousClicked === '=') {
operator = '=';
operand = parseInt(buttonValue);
}
updateDisplay(operand);
}
/**
* Reset the operand
*/
var resetOperand = function () {
operand = 0;
}
/**
* Given the current value, an operand, and operator, calculate the value
*/
var calculate = function (currentValue, operand, operator) {
switch (operator) {
case '+':
return currentValue + operand;
case '-':
return currentValue - operand;
case '*':
return currentValue * operand;
case '/':
return currentValue / operand;
case '=':
return currentValue;
}
}
var updateDisplay = function (displayValue) {
display.value = displayValue
}
for (var i = 0; i < buttons.length; ++i) {
buttons[i].addEventListener('click', pressButton);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment