-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.js
117 lines (115 loc) · 2.77 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
113
114
115
116
117
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(operator, a, b) {
if (!a) return b;
switch (operator) {
case '+':
return add(a, b);
case '-':
return subtract(a, b);
case '*':
return multiply(a, b);
case '/':
return divide(a, b);
default:
return b;
}
}
function clearDisplay() {
display.textContent = '';
}
function appendDigit() {
if (displayToBeCleared) {
clearDisplay();
displayToBeCleared = false;
}
if (display.textContent.length <= 15) {
display.textContent += this.textContent;
}
}
function appendPoint() {
if (!display.textContent.includes('e') && !display.textContent.includes('.')) {
display.textContent += '.';
}
}
function appendResult() {
display.textContent = newNum;
}
function returnResult() {
if (selectedOperator !== '/' || newNum !== '0') {
newNum = operate(selectedOperator, oldNum, newNum);
appendResult();
}
else {
display.textContent = 'Not on my watch - I mean display!'
}
}
function resetAll() {
display.textContent = ''
newNum = null;
oldNum = null;
selectedOperator = null;
}
function storeEquation() {
oldNum = newNum;
newNum = display.textContent;
clearDisplay();
returnResult();
if (this !== equalSign) { selectedOperator = this.textContent; }
displayToBeCleared = true;
}
let newNum;
let oldNum;
let selectedOperator;
displayToBeCleared = false;
const display = document.querySelector('#display');
const operands = document.querySelectorAll('.operand');
const operators = document.querySelectorAll('.operator');
const equalSign = document.querySelector('#equalSign');
const clear = document.querySelector('#clear');
const decimalPoint = document.querySelector('#decimalPoint')
operands.forEach(operand => {
operand.addEventListener('click', appendDigit);
})
operators.forEach(operator => {
operator.addEventListener('click', storeEquation);
})
equalSign.addEventListener('click', storeEquation);
clear.addEventListener('click', resetAll);
decimalPoint.addEventListener('click', appendPoint);
keys = {
"0": "zero",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight",
"9": "nine",
"-": "minus",
"+": "plus",
"*": "times",
"/": "divide",
"c": "clear",
"=": "equalSign",
"Enter": "equalSign"
}
for (const key in keys) {
window.addEventListener('keyup', event => {
if (event.key === key) {
document.getElementById(keys[key]).click();
}
})
}