Skip to content

Commit

Permalink
fix Cannot evaluate for power operator (^) #15
Browse files Browse the repository at this point in the history
  • Loading branch information
raj457036 committed Jul 20, 2024
1 parent ca4d0e0 commit bfc17ab
Showing 1 changed file with 4 additions and 25 deletions.
29 changes: 4 additions & 25 deletions ds.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,27 +238,7 @@ function postfixEval(expression) {
const a = stack.pop();
const b = stack.pop();

let result;
switch (char) {
case "+":
result = `(${b} + ${a})`;
break;
case "-":
result = `(${b} - ${a})`;
break;
case "*":
result = `(${b} * ${a})`;
break;
case "/":
result = `(${b} / ${a})`;
break;
case "^":
result = `(${b} ** ${a})`; // Exponentiation
break;
default:
throw new Error(`Unknown operator: ${char}`);
}

let result = `(${b} ${char} ${a})`;
stack.push(result);
}

Expand All @@ -270,13 +250,12 @@ function postfixEval(expression) {
let _tresult = `${finalResult}`;

try {
_tresult += ` = ${eval(finalResult)}`;
_tresult += ` = ${eval(finalResult.replace(/\^/g, "**"))}`;
} catch (error) {
_tresult += " = Error";
}

table.s[table.s.length - 1] = _tresult;

return table;
}

Expand Down Expand Up @@ -306,8 +285,7 @@ function prefixEval(expression) {
const b = stack.pop();

// Create the expression with current operator
const result = `(${a}${char}${b})`;

let result = `(${b} ${char} ${a})`;
// Push the result back to stack
stack.push(result);
}
Expand All @@ -326,6 +304,7 @@ function prefixEval(expression) {
_tresult += ` = ${eval(finalResult.replace(/\^/g, "**"))}`;
}

_tresult = _tresult.replace("**", "^");
table.s[table.s.length - 1] = _tresult;
return table;
}
Expand Down

0 comments on commit bfc17ab

Please sign in to comment.