ok, so I on to the Javascript calculator. I have it working perfectly (apart form the consecutive operators which I havent started to look at) but I cannot pass tests 11 & 12 (decimal handling - not allowing 2 “.” and decimal calculation). Now on screen that works perfectly (full page for you to look at is : https://robwuk.github.io/FCC_Calc/ and github repo is https://github.com/robwuk/FCC_Calc).
the JS code is below for your perusal - but I am being crude in my code - when user enters a decimal I set the “decimal” flag to true - if another decimal is pressed dont accept… (reset decimal flag to false when user presses and operator or “=” (I need to correct “CLEAR” function - forgot that)). Is there anything obvious as to why the 2 tests wont pass?
var lastAction;
var allActions = new Array();
var equals = false;
var decimal = false;
function clearData() {
lastAction = "0";
allActions.length = 0;
updateTotal();
updateRunningTotal();
}
function updateTotal(){
document.getElementById("display").innerHTML = lastAction;
}
function updateRunningTotal(){
var runningTotal = "";
if (allActions.length==0) {
runningTotal = "0";
} else {
for (let i=0; i < allActions.length; i++) {
runningTotal += allActions[i];
};
}
document.getElementById("display__running").innerHTML = runningTotal;
}
function isOperator(value){
if (value ==="+" || value ==="-" || value ==="/" || value ==="*") {
return true;
} else {
return false;
}
}
function calculateSum(){
if (allActions.length >= 3) {
let value1 = allActions[0];
let operator = allActions[1];
let value2 = allActions[2];
value1 = getResult(parseFloat(value1), operator, parseFloat(value2));
for (let i = 3; i< allActions.length; i+=2) {
if (allActions.length - i >= 2) {
operator = allActions[i];
value2 = allActions[i+1];
value1 = getResult(parseFloat(value1), operator, parseFloat(value2));
}
}
lastAction = value1.toString();
updateTotal();
}
}
function getResult(v1, op, v2){
switch (op) {
case "+":
return v1 + v2;
break;
case "*":
return v1 * v2;
break;
case "-":
return v1 - v2;
break;
case "/":
return v1 / v2;
break;
}
}
function buttonPress(value){
switch (value) {
case "+": case "-": case "/": case "*":
if (equals) {
allActions.length = 0;
allActions.push(lastAction);
}
allActions.push(value);
lastAction = value;
equals = false;
decimal = false;
break;
case "=":
equals = true;
calculateSum();
decimal = false;
break;
case ".":
equals = false;
if (!decimal){
if (isOperator(lastAction)) {
lastAction="0.";
} else {
allActions.pop();
lastAction = lastAction.concat(value);
}
allActions.push(lastAction);
}
decimal = true;
break;
default:
if (equals) {
lastAction = "";
allActions.length = 0;
} else if (isOperator(lastAction)) {
lastAction = "";
} else if (lastAction =="0"){
allActions.pop();
lastAction="";
} else {
allActions.pop();
}
lastAction = lastAction.concat(value);
allActions.push(lastAction);
equals = false;
}
updateRunningTotal();
updateTotal();
}
window.onload=clearData();