Created
January 12, 2021 11:04
-
-
Save anushshukla/97a199c6224f3edb065a7504bdb89d2b to your computer and use it in GitHub Desktop.
Mathematical Expression String Evaluation
This file contains hidden or 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
| const calculate = (num1, operator, num2) => { | |
| switch (operator) { | |
| case '+': return num1 + num2; | |
| case '-': return num1 - num2; | |
| case '*': return num1 * num2; | |
| case '/': return num1 / num2; | |
| } | |
| } | |
| const isOperator = str => ['+','-', '*', '/'].includes(str); | |
| const isLowerPrecedingOperator = str => ['+','-'].includes(str); | |
| const isHighPrecedingOperator = str => ['*','/'].includes(str); | |
| const isOpeningBrace = str => str === '('; | |
| const isClosingBrace = str => str === ')'; | |
| function Calculator(inputs, lowerOperationsOnly) { | |
| let nestedInputs = ''; | |
| let isBraceOpen; | |
| let evaluated = 0; | |
| const stack = []; | |
| for (let index = 0; index < inputs.length; index++) { | |
| let input = inputs[index]; | |
| stack.push(input); | |
| // console.log('stack', stack); | |
| if (isClosingBrace(input)) { | |
| isBraceOpen = false; | |
| input = Calculator(nestedInputs); | |
| let nestedInputsLength = nestedInputs.length + 2; | |
| while (nestedInputsLength) { | |
| stack.pop(); | |
| nestedInputsLength--; | |
| } | |
| nestedInputs = ''; | |
| stack.push(input); | |
| const nextInput = inputs[index + 1]; | |
| if (nextInput && !isOperator(nextInput)) { | |
| stack.push('*'); | |
| } | |
| } | |
| if (isBraceOpen) { | |
| nestedInputs += input; | |
| continue; | |
| } | |
| if (isOpeningBrace(input)) { | |
| isBraceOpen = true; | |
| continue; | |
| } | |
| const prevInput = stack[stack.length - 2]; | |
| const isLastIndex = index === inputs.length - 1; | |
| const canCompute = isHighPrecedingOperator(prevInput) | |
| || isLastIndex | |
| || (lowerOperationsOnly && isLowerPrecedingOperator(prevInput)); | |
| if (canCompute) { | |
| const isNegativeNo = stack[stack.length - 4] === '-' ? -1 : 1; | |
| const prevToPrevInput = (stack[stack.length - 3] || 0)*isNegativeNo; | |
| evaluated = Math.abs(calculate(parseInt(prevToPrevInput), prevInput, parseInt(input))); | |
| // console.log(prevToPrevInput, prevInput, input, '=', evaluated) | |
| stack.pop(); | |
| stack.pop(); | |
| stack.pop(); | |
| stack.push(evaluated); | |
| if (stack.length > 1) { | |
| evaluated = Calculator(stack, true); | |
| while(stack.length) { | |
| stack.pop(); | |
| } | |
| stack.push(evaluated); | |
| } | |
| } | |
| } | |
| return evaluated; | |
| } | |
| // keep this function call here | |
| console.log(Calculator(readline())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment