Skip to content

Instantly share code, notes, and snippets.

@Tobur
Last active November 2, 2018 13:08
Show Gist options
  • Save Tobur/3013f293c86aba42222dfc9a02fd7788 to your computer and use it in GitHub Desktop.
Save Tobur/3013f293c86aba42222dfc9a02fd7788 to your computer and use it in GitHub Desktop.
//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