forked from J404Simpson/calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
104 lines (94 loc) · 2.35 KB
/
calculator.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
var entries = [];
var input = "";
var result = 0;
const display = document.getElementById("display"); //access the html input tag with id = display
listen();
function listen() {
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", buttonEffect);
}
}
function buttonEffect() {
var button = event.target.textContent; //retrieve text between button tags
if (button === "AC") {
//reset all variables
allClear();
} else if (button === "C") {
//reset the last entry
clear();
} else if (button === "Ans") {
reusePreviousAnswer();
} else if (button === "=") {
//Perform operation
calculate();
} else if (!isNaN(button) || button === ".") {
isNumber(button);
} else {
storeNumber(button);
}
}
function allClear() {
entries = [];
input = "";
result = 0;
display.value = "0";
}
function clear() {
input = "";
display.value = entries.join(" ");
}
function reusePreviousAnswer() {
input = result.toString();
display.value = entries.join(" ") + " " + input;
}
function calculate() {
entries.push(input);
input = "";
result = parseInt(entries[0], 10);
for (var i = 1; i < entries.length; i += 2) {
var operator = entries[i];
var num = parseInt(entries[i + 1]);
if (operator === "+") {
result += num;
}
if (operator === "-") {
result -= num;
}
if (operator === "*") {
result *= num;
}
if (operator === "/") {
result /= num;
}
}
entries = [];
display.value = result;
}
function isNumber(button) {
if (button !== "." && input === "0") {
//do not add multiple zeros at the start and replace 0 by digit
input = button;
} else if (input.includes(".") && button === ".") {
//prevent from adding a . if one is already there
return;
} else {
input += button;
}
display.value = entries.join(" ") + " " + input; //Keep the full formula in display field
}
function storeNumber(button) {
if (entries.length > 0 && input === "") {
//Replace operator if pressing a new one
entries[entries.length - 1] = button;
} else if (input === "") {
//Reuse previous result immediately
entries.push(result);
entries.push(button);
} else {
entries.push(input);
entries.push(button);
input = "";
}
display.value = entries.join(" ");
}