-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
84 lines (73 loc) · 2.35 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
let firstOperand = 0;
let secondOperand = 0;
let operator = "";
let displayValue = "";
const displayElement = document.getElementById("display-element");
const numberButtons = document.querySelectorAll(".number-button");
const operatorButtons = document.querySelectorAll(".operator-button");
const decimalButton = document.getElementById("decimal-button");
const calculateButton = document.getElementById("calculate-button");
const clearButton = document.getElementById("clear-button");
const backspaceButton = document.getElementById("backspace-button");
add = () => firstOperand + secondOperand;
subtract = () => firstOperand - secondOperand;
multiply = () => firstOperand * secondOperand;
divide = () => {
if (secondOperand == 0) {
alert("Nice try!!");
return null;
}
return firstOperand / secondOperand;
};
operate = () => {
if (operator == "+") return add();
else if (operator == "-") return subtract();
else if (operator == "*") return multiply();
else if (operator == "/") return divide().toFixed(3);
};
populateDisplay = (itemToDisplay) => {
displayElement.innerText = itemToDisplay;
};
numberButtons.forEach((numberButton) => {
numberButton.addEventListener("click", () => {
displayValue += numberButton.value;
populateDisplay(displayValue);
});
});
operatorButtons.forEach((operatorButton) => {
operatorButton.addEventListener("click", () => {
if (operator) {
secondOperand = parseFloat(displayValue);
displayValue = operate();
populateDisplay(displayValue);
}
operator = operatorButton.value;
populateDisplay(`${displayValue} ${operator}`);
firstOperand = parseFloat(displayValue);
displayValue = "";
});
});
calculateButton.addEventListener("click", () => {
secondOperand = parseFloat(displayValue);
displayValue = operate();
populateDisplay(`= ${displayValue}`);
secondOperand = parseFloat(displayValue);
operator = "";
});
decimalButton.addEventListener("click", () => {
if (!displayValue.includes(".")) {
displayValue += decimalButton.value;
populateDisplay(displayValue);
}
});
clearButton.addEventListener("click", () => {
firstOperand = 0;
secondOperand = 0;
operator = "";
displayValue = "";
populateDisplay(displayValue);
});
backspaceButton.addEventListener("click", () => {
displayValue = displayValue.slice(0, -1);
populateDisplay(displayValue);
});