-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
45 lines (38 loc) · 1.36 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const display = document.getElementById("display");
//const equalsBtn = document.getElementById("equalsBtn");
clearDisplay();
function appendToDisplay(input){
display.value += input;
let equationComponents = display.value.match(/[^\d()]+|[\d.]+/g);
if (equationComponents.length > 3){
calculate();
}
}
function clearDisplay(){
display.value = "";
}
function calculate(){
let equationComponents = display.value
.match(/[^\d()]+|[\d.]+/g)
.slice(0,3);
const firstOperand = equationComponents[0];
const operator = equationComponents[1].slice(0,1);
const secondOperand = equationComponents[2];
if (operator == "+"){
try {display.value = Number(firstOperand) + Number(secondOperand);}
catch(error){display.value = "Error";}
}
else if (operator == "*"){
try {display.value = Number(firstOperand) * Number(secondOperand);}
catch(error){display.value = "Error";}
}
else if (operator == "-"){
try {display.value = Number(firstOperand) - Number(secondOperand);}
catch(error){display.value = "Error";}
}
else if (operator == "/"){
try {display.value = Number(firstOperand) / Number(secondOperand);}
catch(error){display.value = "Error";}
}
console.log(firstOperand, operator, secondOperand);
}