From 727c53a4e65ac45785e3b9b6e18c4b27768dab6b Mon Sep 17 00:00:00 2001 From: Calvin Quinn Date: Tue, 30 Jun 2020 16:40:51 -0400 Subject: [PATCH] passed all tests/after fixing one test case --- assets/js/numbers.js | 68 ++++++++++++++++++++++++++++++++++++++++++-- index.html | 3 -- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/assets/js/numbers.js b/assets/js/numbers.js index 5a925a6..7d6bbb1 100644 --- a/assets/js/numbers.js +++ b/assets/js/numbers.js @@ -1,3 +1,67 @@ function compute(expression) { - // TODO - write method definition here -} \ No newline at end of file + var flag = -1; //keep track of */ operations + var result = 0; + var op = new Array(); + var val = new Array(); + var num = ""; + for(var i = 0; i <= expression.length; i++){ + if(i == expression.length){ + if(flag == 1) { + var o = op.pop(); + if(o == "*"){ + val.push(parseInt(num) * val.pop()); + } + else if(o == "/"){ + val.push( val.pop() / parseInt(num)); + } + flag = -1; + } + } + if(expression[i] == "+" || expression[i] == "-"){ + if(flag == 1) { + var o = op.pop(); + if(o == "*"){ + val.push(parseInt(num) * val.pop()); + } + else if(o == "/"){ + val.push(val.pop() / parseInt(num)); + } + flag = -1; + } + else { + val.push(parseInt(num)); + } + op.push(expression[i]); + num = ""; + } + else if(expression[i] == "*" || expression[i] == "/"){ + if (flag == 1){ + var o = op.pop(); + if(o == "*"){ + val.push(parseInt(num) * val.pop()); + } + if(o == "/"){ + val.push(val.pop() / parseInt(num)); + } + } + else {flag = 1; + val.push(parseInt(num)); + } + op.push(expression[i]); + num = ""; + } + else { + num = num + expression[i]; + } + } + val.push(parseInt(num)); + + num = val[0]; + for(var index = 0; index < op.length; index ++){ + if(op[index] == "+") + num = num + val[index+1]; + else num = num - val[index+1]; + } + return num; +} + diff --git a/index.html b/index.html index acab3b9..e4cbb4d 100644 --- a/index.html +++ b/index.html @@ -35,9 +35,6 @@ - - -