-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.js
97 lines (75 loc) · 2.03 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
function numEvent() {
if (['0', '-0'].includes(secondOperand))
secondOperand = secondOperand.slice(0, -1);
secondOperand += event.srcElement.textContent;
}
function dotEvent() {
if (!secondOperand.includes('.'))
secondOperand += '.';
}
function operatorEvent() {
let currentOp = event.srcElement.textContent;
if (lastKey === 'operator' && currentOp === '-'){
secondOperand = '-0';
update();
return;
}
else if (lastKey === 'number')
calculate();
pressedOperator = currentOp;
lastKey = 'operator';
}
function calculate() {
if (lastKey === 'operator')
secondOperand = firstOperand;
let num1 = Number(firstOperand);
let num2 = Number(secondOperand);
firstOperand = operations[pressedOperator](num1, num2);
update(firstOperand);
lastKey = 'equal';
}
// --------------------------------- //
let firstOperand;
let secondOperand;
let pressedOperator;
let lastKey;
let operations = {
'/': (num1, num2) => num1 / num2,
'*': (num1, num2) => num1 * num2,
'-': (num1, num2) => num1 - num2,
'+': (num1, num2) => num1 + num2,
'none': (num1, num2) => num2
};
function init() {
firstOperand = '0';
secondOperand = '0';
pressedOperator = 'none';
lastKey = 'number';
update();
}
function update(operand) {
if (operand === undefined)
operand = secondOperand;
display.textContent = operand.toString().slice(0, 12);
lastKey = 'number';
}
function checkBeforeNumber() {
if (lastKey === 'equal')
init();
else if (lastKey === 'operator')
secondOperand = '0';
}
let events = keyEvent => {
checkBeforeNumber();
keyEvent();
update();
};
window.onload = () => {
let nums = document.querySelectorAll('.number');
[...nums].forEach(n => n.onclick = () => events(numEvent));
let ops = document.querySelectorAll('.operator');
[...ops].forEach(o => o.onclick = operatorEvent);
dot.onclick = () => events(dotEvent);
equal.onclick = calculate;
init();
};