I’m currently developing a calculator and want to incorporate memory features. Specifically, I need to implement four memory functions: memory recall (MR), memory clear (MC), memory add (M+), and memory subtract (M-).
My plan is to create separate functions for each memory operation and to use distinct variables to maintain the memory values. Is this a conventional method for handling memory in calculators, or is there a more optimized way?
Additionally, I would appreciate it if someone could check my code and point out any potential errors. The display for the calculator is managed by an element with the ID ‘number-display’.
$(document).ready(function(){
var screenValue = "";
var mathOperators = ["/", "*", "-", "+"];
var hasDecimal = false;
$("button").click(function() {
var buttonText = $(this).text();
function refreshScreen() {
if (screenValue.length > 19) {
$("#number-display").html(screenValue.substr(screenValue.length - 19, screenValue.length));
} else {
$("#number-display").html(screenValue.substr(0, 19));
}
}
if (buttonText === "AC" || buttonText === "ON" || buttonText === "MC") {
hasDecimal = false;
screenValue = "";
$("#number-display").html("0");
}
else if (buttonText === "OFF") {
hasDecimal = false;
screenValue = "";
$("#number-display").html("");
}
else if (buttonText === "CE") {
if (screenValue.substr(screenValue.length - 1, screenValue.length) === ".") {
hasDecimal = false;
}
screenValue = screenValue.substr(0, screenValue.length - 1);
refreshScreen();
}
else if (!isNaN(buttonText)) {
screenValue += buttonText;
refreshScreen();
}
else if (buttonText === ".") {
if (!hasDecimal) {
if(screenValue > 0){
screenValue += buttonText;
}
else {
screenValue += "0" + buttonText;
}
hasDecimal = true;
refreshScreen();
}
}
else if (mathOperators.indexOf(buttonText) > -1) {
hasDecimal = false;
if (screenValue.length > 0 && !isNaN(screenValue.substr(screenValue.length - 1, screenValue.length))) {
screenValue += buttonText;
refreshScreen();
}
else if (screenValue.length === 0 && buttonText === "-") {
screenValue += buttonText;
refreshScreen();
}
}
else if ($(this).id === "sqrt") {
var tempValue = screenValue.html();
$("#number-display").html(eval(Math.sqrt(tempValue)));
hasDecimal = false;
}
else if ($(this).id === "plusmn") {
var negativeNum = screenValue * -1;
$("#number-display").html(negativeNum);
}
else if (buttonText === "M-") {
// Memory subtract implementation needed
}
else if (buttonText === "M+") {
// Memory add implementation needed
}
else if (buttonText === "%"){
// Percentage function needed
}
else if (buttonText == "=") {
if (isNaN(screenValue.substr(screenValue.length - 1, screenValue.length))) {
screenValue = screenValue.substr(0, screenValue.length - 1);
}
var result = screenValue;
result = eval(result);
screenValue = String(result);
if (screenValue.indexOf('.')) {
hasDecimal = true;
} else {
hasDecimal = false;
}
$("#number-display").html(screenValue);
}
});
});