Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created January 12, 2021 11:04
Show Gist options
  • Select an option

  • Save anushshukla/97a199c6224f3edb065a7504bdb89d2b to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/97a199c6224f3edb065a7504bdb89d2b to your computer and use it in GitHub Desktop.
Mathematical Expression String Evaluation
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