Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 71 additions & 16 deletions Calculator/saikrishna823/calculator.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,71 @@
let inputBtn=document.getElementById("inputBtn")
let buttons=document.querySelectorAll(".button");
const evalButton=document.getElementById("evalButton");
const clearBtn=document.querySelector(".clearBtn");
buttons.forEach((button)=>{
button.onclick=()=>{
inputBtn.value+=button.textContent;
}
})
;
evalButton.onclick=()=>{
inputBtn.value=eval(inputBtn.value);
}
clearBtn.onclick=()=>{
inputBtn.value=" ";
}
const inputBtn = document.getElementById("inputBtn");
const buttons = document.querySelectorAll(".button");
const evalButton = document.getElementById("evalButton");
const clearBtn = document.querySelector(".clearBtn");

const operators = ["+", "-", "*", "/"];

function showError(message) {
inputBtn.value = message;
inputBtn.classList.add("error");
}

function clearError() {
inputBtn.classList.remove("error");
if (inputBtn.value === "Invalid input" || inputBtn.value === "Cannot divide by zero") {
inputBtn.value = "";
}
}

function isValidExpression(expression) {
if (!expression) {
return false;
}

if (!/^[0-9+\-*/. ]+$/.test(expression)) {
return false;
}

const firstCharacter = expression.charAt(0);
const lastCharacter = expression.charAt(expression.length - 1);

if (operators.includes(firstCharacter) || operators.includes(lastCharacter)) {
return false;
}

return !/[+\-*/]{2,}/.test(expression);
}

buttons.forEach((button) => {
button.onclick = () => {
clearError();
inputBtn.value += button.textContent;
};
});

evalButton.onclick = () => {
clearError();

const expression = inputBtn.value.trim();
if (!isValidExpression(expression)) {
showError("Invalid input");
return;
}

try {
const result = Function(`"use strict"; return (${expression})`)();
if (!Number.isFinite(result)) {
showError("Cannot divide by zero");
return;
}

inputBtn.value = result;
} catch (error) {
showError("Invalid input");
}
};

clearBtn.onclick = () => {
inputBtn.value = "";
inputBtn.classList.remove("error");
};
22 changes: 13 additions & 9 deletions Calculator/saikrishna823/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,20 @@ body{
#evalButton:hover,focus,active{
outline: none;
}
#inputBtn{
border-radius:4px;
height:28px;
width:220px;
}
.clearBtn{
border-radius:3px;
padding:2px;
#inputBtn{
border-radius:4px;
height:28px;
width:220px;
}
#inputBtn.error{
color: #b91c1c;
border: 2px solid #b91c1c;
}
.clearBtn{
border-radius:3px;
padding:2px;
text-align: center;
font-size: larger;
color: white;
background-color:rgb(239, 14, 194);
}
}