Last active
November 2, 2018 13:08
-
-
Save Tobur/3013f293c86aba42222dfc9a02fd7788 to your computer and use it in GitHub Desktop.
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
//It works only with + and - operation | |
//If need to use operations like * or / and so on: need to add prioriry of operations | |
//Also exist algoritm with "stack" and "recursion". | |
//Current algoritm is most simple way for equialent operations. | |
var str = "1-(2-3-(4-5))+6-(8-10)+(3+4)"; | |
function _calculate(a, op, b) { | |
a = a * 1; | |
b = b * 1; | |
switch (op) { | |
case '+': | |
return a + b; | |
case '-': | |
return a - b; | |
} | |
} | |
function calculateStr(input) { | |
input = input.replace(/^[^0-9]|\\-|\\+|\(|\)/g, ''); // clean up unnecessary characters | |
var output; | |
//Parse by one | |
var re = new RegExp('(\\d+\\.?\\d*)([\+\-])(\\d+\\.?\\d*)'); | |
// execute all | |
while (re.test(input)) { | |
output = _calculate(RegExp.$1, RegExp.$2, RegExp.$3); | |
if (isNaN(output) || !isFinite(output)) { | |
return output; // exit early if not a number | |
} | |
input = input.replace(re, output); | |
} | |
return output; | |
} | |
console.info(str); | |
console.info(calculateStr(str)); | |
console.info('Check:'); | |
console.info(eval(str)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment