-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
70 lines (60 loc) · 2.14 KB
/
Copy pathscript.js
File metadata and controls
70 lines (60 loc) · 2.14 KB
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
const calculator = document.querySelector('.calculator');
const keys = calculator.querySelector('.keys');
const display = document.getElementById('display');
keys.addEventListener('click', e => {
if (!e.target.matches('button')) return;
const key = e.target;
const action = key.dataset.action;
const keyContent = key.textContent;
const displayedNum = display.textContent;
if (!action) {
if (displayedNum === '0' || calculator.dataset.previousKeyType === 'operator') {
display.textContent = keyContent;
} else {
display.textContent = displayedNum + keyContent;
}
calculator.dataset.previousKeyType = 'number';
}
if (
action === 'add' ||
action === 'subtract' ||
action === 'multiply' ||
action === 'divide'
) {
calculator.dataset.firstValue = displayedNum;
calculator.dataset.operator = action;
calculator.dataset.previousKeyType = 'operator';
}
if (action === 'decimal') {
if (!displayedNum.includes('.')) {
display.textContent = displayedNum + '.';
}
calculator.dataset.previousKeyType = 'decimal';
}
if (action === 'clear') {
display.textContent = '0';
calculator.dataset.firstValue = '';
calculator.dataset.operator = '';
calculator.dataset.previousKeyType = 'clear';
}
if (action === 'calculate') {
const firstValue = calculator.dataset.firstValue;
const operator = calculator.dataset.operator;
const secondValue = displayedNum;
display.textContent = calculate(firstValue, operator, secondValue);
calculator.dataset.previousKeyType = 'calculate';
}
});
function calculate(n1, operator, n2) {
let result = '';
if (operator === 'add') {
result = parseFloat(n1) + parseFloat(n2);
} else if (operator === 'subtract') {
result = parseFloat(n1) - parseFloat(n2);
} else if (operator === 'multiply') {
result = parseFloat(n1) * parseFloat(n2);
} else if (operator === 'divide') {
result = parseFloat(n1) / parseFloat(n2);
}
return result;
}