-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathscript.js
82 lines (79 loc) · 2.14 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
function getHistory() {
return document.getElementById("history-value");
}
function printHistory(num) {
document.getElementById("history-value").innerText = num;
}
function getOutput() {
return document.getElementById("output-value").innerText;
}
function printOutput(num) {
document.getElementById("output-value").innerText = num;
}
var lst = ["%", "/", "+", "-", "*"];
var f = false;
var operator = document.getElementsByClassName("number");
for (var i = 0; i < operator.length; i++) {
operator[i].addEventListener("click", function () {
if (this.id == "clear") {
printHistory("");
printOutput("");
} else if (this.id == "backspace") {
var output = getOutput();
if (output) {
//if output has a value
output = output.substring(0, output.length - 1);
//output = output;
printOutput(output);
}
} else if (this.id == "=") {
try {
var output = getOutput();
if (output == "NaN" || output == "" || f) {
f = false;
printOutput("");
printHistory("");
} else {
var outpu = eval(output);
// print(outpu);
if (outpu == undefined) {
outpu = "NaN";
output = "";
}
f = true;
printOutput(outpu);
printHistory(output);
}
} catch (error) {
outpu = "NaN";
output = "";
f = true;
printOutput(outpu);
printHistory(output);
}
} else {
var output = getOutput().toString();
//console.log(lst[1] == this.id);
if (output.length == 0 && lst.includes(this.id)) {
printOutput("");
printHistory("");
f = false;
} else {
if (f || output == "NaN") {
if (!lst.includes(this.id)) {
output = this.id;
printHistory("");
} else {
output = output + this.id.toString();
}
f = false;
} else {
if (output.length > 0) output = output + this.id.toString();
else output = this.id;
}
console.log(output);
printOutput(output);
}
}
});
}