forked from woowacourse/javascript-calculator
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcalculator.ts
More file actions
47 lines (41 loc) · 1.33 KB
/
calculator.ts
File metadata and controls
47 lines (41 loc) · 1.33 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
import operateResult from "../util/operate.js";
export default function calculator() {
let prevVal: number | undefined = undefined;
let currVal: number | undefined = undefined;
let op = '';
const totalH1 = document.getElementById('total');
function onDigitClicked(e: Event) {
if (currVal === undefined || op === '=')
currVal = 0;
if (100 <= currVal && currVal < 1000)
return;
if (e.target instanceof HTMLElement) {
currVal *= 10;
currVal += Number(e.target.innerHTML);
}
totalH1!.innerHTML = String(currVal);
}
function onOperationClicked(e: Event) {
if (currVal !== undefined) {
prevVal = operateResult(prevVal ?? 0, currVal ?? 0, op);
currVal = undefined;
totalH1!.innerHTML = String(prevVal);
}
if (e.target instanceof HTMLElement) {
op = e.target.innerHTML;
if (op === '=') {
currVal = prevVal;
prevVal = undefined;
}
}
}
function onACClicked() {
prevVal = undefined;
currVal = undefined;
op = '';
totalH1!.innerHTML = '0';
}
document.getElementsByClassName('digits')[0].addEventListener('click', onDigitClicked);
document.getElementsByClassName('operations')[0].addEventListener('click', onOperationClicked);
document.getElementsByClassName('modifier')[0].addEventListener('click', onACClicked);
}