Skip to content

Commit 707daa0

Browse files
Merge pull request steam-bell-92#646 from Pratikshya32/fix/calculator-operator-chaining
fix: handle Infinity results and improve eval safety in calculator
2 parents 600d365 + 121dee1 commit 707daa0

1 file changed

Lines changed: 10 additions & 18 deletions

File tree

web-app/js/projects/calculator.js

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -326,9 +326,11 @@ function initCalculator() {
326326

327327
function safeEval(expr) {
328328
try {
329-
const cleaned = sanitize(expr);
330-
if (!cleaned) return "";
331-
return String(evaluateExpression(normalize(cleaned)));
329+
if (!expr) return "";
330+
let result = Function('"use strict"; return (' + format(expr) + ')')();
331+
if (result === undefined) return "";
332+
if (isNaN(result)) return "Error";
333+
return String(result);
332334
} catch {
333335
return "Error";
334336
}
@@ -457,21 +459,11 @@ function initCalculator() {
457459
}
458460
}
459461

460-
function evaluateCurrent() {
461-
const evaluated = safeEval(expression);
462-
expression = evaluated || "";
463-
update();
464-
}
465-
466-
function deleteLast() {
467-
clearIfError();
468-
expression = expression.slice(0, -1);
469-
update();
470-
}
471-
472-
function clearExpression() {
473-
expression = "";
474-
update();
462+
463+
function clearIfFinished() {
464+
if (expression === "Error" || expression === "NaN" || expression === "Infinity" || expression === "-Infinity") {
465+
expression = "";
466+
}
475467
}
476468

477469
document.querySelectorAll(".calc-btn").forEach(btn => {

0 commit comments

Comments
 (0)