-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
117 lines (98 loc) · 2.38 KB
/
scripts.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const display = document.querySelector("#screen");
const calculator = document.querySelector(".container");
calculator.addEventListener("click", (e) => {
const btnType = e.target.getAttribute("class");
if (btnType === "clear button"){
clearButtonClick(e);
}
if (require_clear) {
return;
}
if (btnType === "number button") {
numberButtonClick(e);
} else if (btnType === "op button") {
opButtonClick(e);
} else if (btnType === "eq button") {
eqButtonClick(e);
}
});
const operations = {
"+": add,
"-": subtract,
"/": divide,
"x": multiply,
}
let has_op = false;
let can_eval = false;
let require_clear = false;
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
return a / b;
}
function operate(a, b, op) {
return operations[op](a, b);
}
function parseExpression() {
let [left, op, right] = display.textContent.split(" ")
return [parseFloat(left), op, parseFloat(right)]
}
function displayError(text) {
display.textContent = text;
require_clear = true;
}
function evalScreen() {
let [left, op, right] = parseExpression()
if (right === 0 && op === "/"){
displayError("can't divide by 0!")
return;
}
let result = operate(left, right, op);
let temp = String(result);
let len = temp.length;
if (len > 13 && temp.includes(".")){
let numDecimals = 13 - temp.indexOf(".") + 1
result = result.toFixed(numDecimals)
}
display.textContent = result;
has_op = false;
can_eval = false;
}
function numberButtonClick(event) {
text = display.textContent;
display.textContent = display.textContent + event.target.textContent;
if (has_op) {
can_eval = true;
}
}
function opButtonClick(event) {
if (has_op) {
if (can_eval){
evalScreen();
}
}
has_op = true;
op = event.target.textContent;
text = display.textContent;
display.textContent = text + " " + op + " ";
}
function clearScreen() {
display.textContent = "";
has_op = false;
can_eval = false;
require_clear = false;
}
/* wrappers for consistency and because they may be useful later */
function eqButtonClick(event) {
evalScreen();
}
function clearButtonClick(event){
clearScreen();
}