-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
72 lines (61 loc) · 2.33 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
63
64
65
66
67
68
69
70
71
72
let currentInput = ""; // Initialize the current input value.
let memory = 0; // Initialize the memory variable.
function updateDisplay() {
document.getElementById("operation").value = currentInput; // Update the display with the current input value.
}
function appendToDisplay(value) {
currentInput += value; // Append the provided value to the current input.
updateDisplay();
}
function appendZero(value) {
if (currentInput.slice(-1) !== ".") {
currentInput += value; // Append the provided value (dot) to the current input if the last character is not already a dot.
}
updateDisplay();
}
function clearDisplay() {
currentInput = ""; // Clear the current input value.
updateDisplay();
}
function calculateResult(operation) {
if (operation === "=") {
try {
currentInput = eval(currentInput); // Evaluate the current input as a mathematical expression.
} catch (error) {
currentInput = "Error"; // Handle errors and display "Error" if evaluation fails.
}
} else if (operation === "1/X") {
currentInput = 1 / parseFloat(currentInput); // Calculate the reciprocal (1/X) of the current input.
} else if (operation === "x2") {
currentInput = Math.pow(parseFloat(currentInput), 2); // Square (x2) the current input.
} else if (operation === "√") {
currentInput = Math.sqrt(parseFloat(currentInput)); // Calculate the square root (√) of the current input.
}
updateDisplay();
}
function toggleSign() {
currentInput = (parseFloat(currentInput) * -1).toString(); // Toggle the sign of the current input.
updateDisplay();
}
function memoryClear() {
memory = 0; // Clear the memory value.
}
function memoryRecall() {
currentInput = memory.toString(); // Recall the value from memory and set it as the current input.
updateDisplay();
}
function memoryAppend() {
if (/[+\-/*]/.test(currentInput)) {
console.log(memory);
return; // Do not add to memory if operators are present in currentInput.
} else {
memory = parseFloat(currentInput); // Add the current input to memory if it doesn't contain operators.
console.log(memory);
}
}
function memoryAdd() {
memory += parseFloat(currentInput); // Add the current input to the memory value.
}
document.addEventListener("DOMContentLoaded", function () {
updateDisplay(); // Initialize the display with the current input value.
});