-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
120 lines (93 loc) · 2.5 KB
/
main.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
118
119
120
"use strict";
const input = document.querySelector(".input");
const result = document.querySelector(".result");
const deleteBtn = document.querySelector(".delete");
const keys = document.querySelectorAll(".bottom span");
let operation = "";
let answer;
let decimalAdded = false;
const operators = ["+", "-", "x", "÷"];
function handleKeyPress (e) {
const key = e.target.dataset.key;
const lastChar = operation[operation.length - 1];
if (key === "=") {
return;
}
if (key === "." && decimalAdded) {
return;
}
if (operators.indexOf(key) !== -1) {
decimalAdded = false;
}
if (operation.length === 0 && key === "-") {
operation += key;
input.innerHTML = operation;
return;
}
if (operation.length === 0 && operators.indexOf(key) !== -1) {
input.innerHTML = operation;
return;
}
if (operators.indexOf(lastChar) !== -1 && operators.indexOf(key) !== -1) {
operation = operation.replace(/.$/, key);
input.innerHTML = operation;
return;
}
if (key) {
if (key === ".") decimalAdded = true;
operation += key;
input.innerHTML = operation;
return;
}
}
function evaluate(e) {
const key = e.target.dataset.key;
const lastChar = operation[operation.length - 1];
if (key === "=" && operators.indexOf(lastChar) !== -1) {
operation = operation.slice(0, -1);
}
if (operation.length === 0) {
answer = "";
result.innerHTML = answer;
return;
}
try {
if (operation[0] === "0" && operation[1] !== "." && operation.length > 1) {
operation = operation.slice(1);
}
const final = operation.replace(/x/g, "*").replace(/÷/g, "/");
answer = +(eval(final)).toFixed(5);
if (key === "=") {
decimalAdded = false;
operation = `${answer}`;
answer = "";
input.innerHTML = operation;
result.innerHTML = answer;
return;
}
result.innerHTML = answer;
} catch (e) {
if (key === "=") {
decimalAdded = false;
input.innerHTML = `<span class="error">${operation}</span>`;
result.innerHTML = `<span class="error">Bad Expression</span>`;
}
console.log(e);
}
}
function clearInput (e) {
if (e.ctrlKey) {
operation = "";
answer = "";
input.innerHTML = operation;
result.innerHTML = answer;
return;
}
operation = operation.slice(0, -1);
input.innerHTML = operation;
}
deleteBtn.addEventListener("click", clearInput);
keys.forEach(key => {
key.addEventListener("click", handleKeyPress);
key.addEventListener("click", evaluate);
});