Skip to content

Instantly share code, notes, and snippets.

@eokoneyo
Last active January 31, 2020 15:30
Show Gist options
  • Save eokoneyo/892b413bcc7d670cc32810bd4adb8520 to your computer and use it in GitHub Desktop.
Save eokoneyo/892b413bcc7d670cc32810bd4adb8520 to your computer and use it in GitHub Desktop.
const validOps = ['+', '-', '*', '/'];
const compute = (rightOperand, leftOperand, operation) => {
switch (operation) {
case '+':
return leftOperand + rightOperand;
case '-':
return leftOperand - rightOperand;
case '*':
return leftOperand * rightOperand;
case '/':
return leftOperand / rightOperand;
default:
return leftOperand;
}
}
const calculate = (expression) => {
const stack = []
const evaluated = expression.split(' ');
evaluated.forEach(value => {
if (validOps.indexOf(value) < 0) {
if(Number.isNaN(value)) {
console.warn('Unsupported operand! %s was found skipping... ', value);
} else {
stack.push(Number(value))
};
} else {
stack.push(compute(stack.pop(), stack.pop(), value));
}
});
return stack.pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment