1
var calculate = function (s) {5
const isNumber = (char) => !isNaN(char);7
function calculate(a, b, op) {8
if (op === "+") return a + b;9
if (op === "-") return a - b;13
for (let i = 0; i < s.length; i++) {16
if (char === " ") continue;24
// i.e. char is not a number so the number has ended25
if (numStack[numStack.length - 1].length === 0) {26
numStack[numStack.length - 1].push(+number);28
const a = numStack[numStack.length - 1].pop();29
const op = opStack.pop();30
numStack[numStack.length - 1].push(calculate(a, +number, op));37
if (numStack[numStack.length - 1].length === 0) {38
numStack[numStack.length - 1].push(0);42
numStack.push([]); // Start a new stack for this parenthesis47
const b = numStack.pop().pop();48
const a = numStack[numStack.length - 1].pop();49
const op = opStack.pop();50
numStack[numStack.length - 1].push(calculate(a, b, op));54
if (char === "+" || char === "-") {55
if (numStack[numStack.length - 1].length === 0) {56
numStack[numStack.length - 1].push(0);63
// We should never reach here64
throw new Error("Unexpected input: " + char);68
if (numStack[numStack.length - 1].length === 0) return +number;70
const a = numStack[numStack.length - 1].pop();71
const op = opStack.pop();72
numStack[0].push(calculate(a, +number, op));75
return numStack.pop().pop();