-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
62 lines (51 loc) · 1.56 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
import {
handleCurrentItem,
isOperator,
getTextNode,
handleOperatorCase,
updateSequenceOnceReady,
} from "./calculator.helper.js";
const initCalculator = () => {
let currentSequence = "",
screenSequence = [],
buttons = document.querySelectorAll("button");
const handleClickEvent = ({ target: { innerHTML } }) => {
const lastCurrentSequenceValue = screenSequence[screenSequence.length - 1],
item = handleCurrentItem({
currentValue: innerHTML,
lastSequenceValue: lastCurrentSequenceValue,
}),
screen = document.getElementById("screen");
if (item) {
const itemValue = item.innerHTML;
if (isOperator(itemValue)) {
currentSequence = "";
screenSequence = handleOperatorCase({
itemValue,
screenSequence,
});
} else {
if (itemValue !== "=") {
currentSequence += itemValue;
if (!isOperator(lastCurrentSequenceValue)) {
screenSequence.pop();
}
screenSequence.push(currentSequence);
}
}
screen.innerHTML = "";
if (itemValue === "=" && screenSequence.length === 3) {
screenSequence = updateSequenceOnceReady(screenSequence);
}
for (let i = 0; i < screenSequence.length; i++) {
screen.appendChild(
getTextNode({ currentValue: screenSequence[i], HTMLTag: "span" })
);
}
}
};
buttons.forEach((button) =>
button.addEventListener("click", handleClickEvent)
);
};
document.addEventListener("DOMContentLoaded", initCalculator);