Last active
March 25, 2021 16:27
-
-
Save deepak-terse/c8aae87a63b5bc757d52837d49eece57 to your computer and use it in GitHub Desktop.
Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Problem Statement: | |
- Have the function Calculator(str) take the str parameter being passed and evaluate the mathematical expression within in. | |
- For example, if str were "2+(3-1)*3" the output should be 8. | |
- Another example: if str were "(2-0)(6/2)" the output should be 6. | |
- There can be parenthesis within the string so you must evaluate it properly according to the rules of arithmetic. | |
- The string will contain the operators: +, -, /, *, (, and ). | |
- If you have a string like this: #/#*# or #+#(#)/#, then evaluate from left to right. So divide then multiply, and for the second one multiply, divide, then add. | |
- The evaluations will be such that there will not be any decimal operations, so you do not need to account for rounding and whatnot. | |
Examples | |
Input: "6*(4/2)+3*1" | |
Output: 15 | |
Input: "6/3-1" | |
Output: 1 | |
*/ | |
//Solves a mathematical expression with 2 operands and a operator | |
function operate(a, b, operator) { | |
a = typeof a == 'string' ? parseInt(a) : a; | |
b = typeof b == 'string' ? parseInt(b) : b; | |
switch(operator){ | |
case "*": return a * b; | |
case "/": return a / b; | |
case "+": return a + b; | |
case "-": return a - b; | |
} | |
return 0; | |
} | |
//Solves brackets and resolves mathematical expression inside it to a number. Uses breakString() method. | |
function removeBrackets(str) { | |
while(str.includes('(')){ | |
var i = str.indexOf(')(') | |
if(i != -1){ | |
str = str.substring(0,i+1) + '*' + str.substring(i+1,str.length); | |
} | |
var str2 = str.substring(str.indexOf("(") + 1, str.indexOf(")")); | |
str = str.replace('('+str2+')', breakString(str2)); | |
} | |
return str; | |
} | |
//Solves a mathematical expression inside it to a number | |
function breakString(str) { | |
var ops = ['-','+','*','/']; | |
var result = 0; | |
for(i=0; i<ops.length; i++) { | |
if(str.includes(ops[i])){ | |
var a = str.substr(0,str.lastIndexOf(ops[i])); | |
var b = str.substr(str.lastIndexOf(ops[i])+1,str.length-1); | |
var op = ops[i]; | |
result = operate( | |
isNaN(a) ? breakString(a): a, | |
isNaN(b) ? breakString(b): b, | |
op | |
); | |
} | |
} | |
return result; | |
} | |
function Calculator(str) { | |
var str2 = removeBrackets(str); | |
return breakString(str2); | |
} | |
console.log(Calculator("(4+5)/(1+2) + 2*(8-5)")); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment