Last active
December 22, 2020 21:59
-
-
Save TravisL12/749c1fd609802badf1d6eb2e1ff9efc9 to your computer and use it in GitHub Desktop.
Calculator function for handling multiple inputs
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
| 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