Last active
November 10, 2016 12:29
-
-
Save sbernhardi/e8ad859e4cddf81cd2911900a08c2297 to your computer and use it in GitHub Desktop.
CF Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var calcStr = ""; // computation String as such - to be eval()uated at the end. | |
var calcDec = false; // toggle for checking if decimal point is set | |
var calcDone = false; // toggle for checking eval() | |
var operand = []; // collecting operands -> dataGathering() | |
var numbers = []; // collecting numbers -> dataGathering() | |
function dataGathering(a){ | |
if (calcStr) { | |
numbers.push(parseFloat(calcStr)); | |
operand.push(a); | |
calcStr = ""; | |
calcDec = false; | |
} | |
} | |
var myMath = { | |
"round": function(number, precision) { | |
var factor = Math.pow(10, precision); | |
return Math.round(number * factor)/factor; | |
} | |
}; | |
function calculate(){ | |
var evt = event.target.id; | |
switch(evt){ | |
case "reset": | |
calcStr = ""; | |
operand = []; | |
numbers = []; | |
break; | |
case "divide": | |
dataGathering("/"); | |
break; | |
case "multiply": | |
dataGathering("*"); | |
break; | |
case "add": | |
dataGathering("+"); | |
break; | |
case "substr": | |
dataGathering("-"); | |
break; | |
case "equals": | |
if(numbers.length > 0){ | |
var calcTemp = calcStr; | |
calcStr = ""; | |
while(numbers.length > 0){ | |
calcStr += numbers.shift() + operand.shift(); | |
} | |
calcStr += calcTemp; | |
calcStr = myMath.round(eval(calcStr),5); | |
calcDone = true; | |
/* | |
* attempt to change the display to exponential | |
* when exceeding screen's limit. | |
* Not yet functioning. Figure out later. | |
var digitCount = (calcStr + '').replace('.', '').length; | |
if (digitCount > 7) calcStr.toExponential(); | |
*/ | |
} | |
break; | |
case "decimal": | |
if (calcStr && !calcDec) calcDec = true; | |
break; | |
default: | |
if (evt.match(/\d/)){ | |
if(calcDone) { | |
calcStr = ""; | |
calcDone = false; | |
} | |
if (calcDec) { | |
calcStr += "."; | |
calcDec = false; | |
} | |
calcStr += evt; | |
} | |
break; | |
} | |
if (numbers.length > 0 && !calcStr) document.getElementById("display").textContent = numbers[numbers.length-1]; | |
else document.getElementById("display").textContent = calcStr; | |
} | |
document.getElementById("calculator").addEventListener("click", calculate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment