-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
151 lines (126 loc) · 2.66 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
function calculator() {
var total = '',
value,
operator,
memory = null,
equal =false;
var butts = document.getElementsByTagName('button');
for (var i = 0; i < butts.length; i++) {
butts[i].addEventListener("mousedown", function (e) {
keypunch(e);
debug();
});
}
function keypunch(e) {
value = e.target.value;
if (/\d/.test(value)||value==".") {
if(value=='0' && total==''){
//do nothing (if total is zero and key pressed is zero)
} else {
if (equal) {
total = '';
operator = null;
equal = false;
memory = null;
}
total += value;
print(total);
}
}
if (value=='+'||value=='-'||value=='/'||value=='*') {
//prevents duplicate press of operator key
if(total){
//if the PREVious operator was not equalled out
if (!equal) {
//
if (operator) {
operation(operator);
operator = value;
total = '';
print(memory);
} else {
memory = Number(total);
operator = value;
total = '';
print(memory);
}
//if Equal key was the PREVious key pressed
} else {
equal = false;
operator = value;
total = '';
print(memory);
}
}
}
if (value=='=') {
if (operator && total) {
operation(operator);
equal = true;
print(memory);
}
}
if (value=='+-') {
if (!equal) {
total = Number(total) * -1;
print(total);
} else {
memory *= -1;
print(memory);
}
}
if (value=='sqrt') {
total = Math.sqrt(Number(total));
print(total);
}
if (value=='c') {
total = '';
print(0);
}
if (value=='cl') {
total = '';
memory = null;
operator = null;
print(0);
}
}
// Helper Functions //
function operation(operator) {
switch(operator){
case "+":
return memory += Number(total);
case "-":
return memory -= Number(total);
case "/":
return memory /= Number(total);
case "*":
return memory *= Number(total);
}
}
function print(something) {
something = something.toString();
//Rounds to max digits of 8 (I think)
if(something.length>8){
if(Number(something.charAt(8))>4){
var end = Number(something.slice(7,8)) + 1;
if(end===10){
}
console.log(end);
console.log(something.slice(0, 7));
something = something.slice(0, 7).concat(end.toString());
}
else{
something = something.slice(0, 8);
}
}
var display = document.getElementById('display');
display.textContent = something;
}
function debug() {
console.log("[ total = "+total+"; \n"+
"operator is "+operator+"; \n"+
"memory = "+memory+"; \n"+
"equal is "+equal+"]")
}
}
window.onload = calculator;