-
Notifications
You must be signed in to change notification settings - Fork 0
/
js.js
79 lines (77 loc) · 1.75 KB
/
js.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
const input = document.querySelector('#monitor');
let fix = 0;
let memory = 0;
input.value = 0;
function calculate() {
fix = input.value
for (i = 0; i < 10; i++) { //fixing multipications like 2(4)
fix = fix.replaceAll(i + '(', i + '*(')
}
fix = fix.replaceAll(")(", ")*("); // fixing multipilications like (4)(2)
input.value = eval(fix);
return eval(fix);
}
function num(x) {
if (input.value == "0") {
input.value = "";
}
input.value += x;
}
function operator(y) { // preventing user from typing two operators in a row
let opr = input.value.charAt(input.value.length - 1)
if (opr != "-" && opr != "*" && opr != "+" && opr != "/" && opr != ".") {
input.value += y;
}
}
function mread() {
input.value += memory;
}
function mclean() {
memory = 0;
}
function mplus() {
memory += calculate();
}
function memoryinus() {
memory -= calculate();
}
function clean() {
input.value = 0;
}
// Codes below adresses the key on the keyboard to the above functions
document.addEventListener('keydown', function(event) {
if (event.keyCode > 95 && event.keyCode < 106) { // numpad keys
let mykey = event.keyCode - 96;
num(mykey);
} else if (event.keyCode == 8) { // backspace
input.value = input.value.substring(0, input.value.length - 1);
} else if (event.keyCode == 13) { // enter
calculate();
}
switch (event.keyCode) {
case 110:
operator(".");
break;
case 107:
operator("+");
break;
case 109:
operator("-");
break;
case 106:
operator("*");
break;
case 111:
operator("/");
break;
case 57:
num("(");
break;
case 48:
num(")");
break;
case 191:
operator("/");
break;
}
});