Skip to content

Instantly share code, notes, and snippets.

@TravisL12
Last active December 22, 2020 21:59
Show Gist options
  • Select an option

  • Save TravisL12/749c1fd609802badf1d6eb2e1ff9efc9 to your computer and use it in GitHub Desktop.

Select an option

Save TravisL12/749c1fd609802badf1d6eb2e1ff9efc9 to your computer and use it in GitHub Desktop.
Calculator function for handling multiple inputs
function operate(num1, num2, operand) {
switch (operand) {
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
return num1 + num2;
}
}
function calc(expression) {
const split = expression.match(/(\d(\.?\d?)+)|([+-/*//])/g);
let amount = +split.splice(0, 1)[0];
while (split.length > 0) {
let[operand,next] = split.splice(0, 2)
amount = operate(amount, +next, operand)
}
return amount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment