CS2613/tests/Final/Q3 Javascript/expression.js
2022-12-20 21:49:28 -04:00

51 lines
1.1 KiB
JavaScript

class Expression {
constructor(op, left, right) {
this.op = op
this.left = left
this.right = right
}
eval() {
return evalExpression(this)
}
}
function evalExpression(expr) {
let tempLeft
let tempRight
if (typeof(expr.left) === "object") { // Check if left type is another expression
tempLeft = evalExpression(expr.left)
}
else {
tempLeft = expr.left
}
if (typeof(expr.right) === "object") { // Check if right type is another expression
tempRight = evalExpression(expr.right)
}
else {
tempRight = expr.right
}
if (typeof(tempLeft) === "number" & typeof(tempRight) === "number") { // Make sure both inputs are number
if (expr.op === "+") {
return tempLeft + tempRight
}
else if(expr.op === "-") {
return tempLeft - tempRight
}
else if(expr.op === "*") {
return tempLeft * tempRight
}
else if(expr.op === "/") {
return tempLeft / tempRight
}
else { // Case for when there is no valid provided operator
return "Invalid operator syntax"
}
}
else { //Case for when the left or right are not numbers
return "Invalid number syntax"
}
}
exports.Expression = Expression;