Skip to content

Instantly share code, notes, and snippets.

@ankr
Last active December 31, 2015 00:19
Show Gist options
  • Save ankr/7907047 to your computer and use it in GitHub Desktop.
Save ankr/7907047 to your computer and use it in GitHub Desktop.
function calc(expression) {
var divmultest = /[\/\*]+/;
var divmulreplace = /(\-?[\d\.]+)\s*(\/|\*)\s*(\-?[\d\.]+)/g;
var addsubtest = /\d+\s*[\+\-]+/;
var addsubreplace = /(\-?[\d\.]+)\s*(\+|\-)\s*(\-?[\d\.]+)/g;
var parens = /\(([^\(\)]+)\)/g;
var evaluate = function (e) {
while (divmultest.test(e)) {
e = e.replace(divmulreplace, function (m, x, o, y) {
return o == '*' ? x * y : x / y;
});
}
while (addsubtest.test(e)) {
e = e.replace(addsubreplace, function (m, x, o, y) {
return o == '+' ? x * 1 + y * 1 : x - y;
});
}
return e;
}
while (expression.indexOf('(') !== -1) {
expression = expression.replace(parens, function (m, e) {
return evaluate(e);
});
}
return +evaluate(expression);
}
calc('123.45*(678.90 / (-2.5+ 11.5)-(80 -19) *33.25) / 20 + 11'); // => -12042.760875
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment