Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
100 lines (83 loc) · 2.27 KB
/
Copy pathscript.js
File metadata and controls
100 lines (83 loc) · 2.27 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
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
let expression = "0";
const DISPLAY = document.getElementById("user-input");
const RESULT = document.getElementById("result");
function appendToDisplay(value) {
// Check for existing decimal in the current number
if (value === "." && /\.\d*$/.test(expression)) {
return;
} else if (isOperator(value)) {
// Replace previous operators
expression = expression.replace(/[-+*/]$/, "");
}
// special case: Prevent appending a zero in front when any number is pressed
if (expression === "0" && !isOperator(value)) {
expression = value;
} else {
expression += value;
}
updateDisplay(expression);
}
function isOperator(value) {
return value === "+" || value === "-" || value === "*" || value === "/";
}
function updateResult() {
RESULT.value = expression;
}
function clearAllDisplay() {
expression = "0";
updateResult();
updateDisplay(expression);
}
function deleteDisplay() {
expression = expression.slice(0, -1);
if (expression == "") {
expression = "0";
}
updateDisplay(expression);
}
function updateDisplay(value) {
//append 0 to expression if the first value is an operator i.e., +2 to be displayed as 0 + 2
if (RESULT.value == "0" && isOperator(value.charAt(0))) {
value = appendZero(value);
}
DISPLAY.value = transformOperators(value);
}
function appendZero(value) {
return "0" + value;
}
function transformOperators(value) {
if (value.includes("*") || value.includes("/")) {
value = value.replace(/\*/g, "×").replace(/\//g, "÷");
}
return value;
}
function calculateResult() {
try {
const result = math.evaluate(expression);
if (Number.isInteger(result)) {
expression = result.toString(); // display whole numbers without trailing zeros
} else {
const resultString = result.toString();
const decimalIndex = resultString.indexOf(".");
// Round up long decimal values to 5 decimal places.
if (
decimalIndex !== -1 &&
resultString.length - decimalIndex > 6
) {
expression = (
Math.round(result * 100000) / 100000
).toString();
} else if (resultString === "Infinity") {
alert("You cannot divide by Zero!");
clearAllDisplay();
} else {
expression = resultString;
}
}
updateResult();
} catch (error) {
alert("Invalid expression");
clearAllDisplay();
}
}
document.onload = clearAllDisplay();