JavaScript (213 characters compacted, 133 if I'm willing to sacrifice my soul)
For clarity, this is the code before I compacted it down (JS-Fiddle of it):
function math(match, leftDigit, operator, rightDigit, offset, string) {
var L = parseInt(leftDigit)
var R = parseInt(rightDigit)
switch (operator)
{
case '*': return R*L;
case '\/': return R/L;
case '+': return L+R;
case '-': return L-R;
}
};
multAndDivRegex = /(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/; //Right to left
addAndSubRegex = /(\-?\d+)([\+\-])(\-?\d+)/; // Left to right
while(multAndDivRegex.test(str)) {
str = str.replace(multAndDivRegex, math);
}
while(addAndSubRegex.test(str)) {
str = str.replace(addAndSubRegex, math);
}
Here it is compacted down to 213 characters (containing some extra help from Toni AlmeidaToni Almeida) (JS-Fiddle of it):
function m(x,l,o,r){
L=~~l;R=~~r;
return o=='*'?R*L:o=='/'?R/L:o=='+'?L+R:L-R
}
for(M=/(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/;M.test(s);s=s.replace(M,m));
for(A=/(\-?\d+)([\+\-])(\-?\d+)/;A.test(r=s);s=s.replace(A,m));
Since I'm ending lines with semi-colons, all removable whitespace was ignored for character counting, but left in for clarity.
I can get it down to 133 characters if I use eval()
, but that's not how I roll... (JS-Fiddle)
function m(x,l,o,r){return o=='*'?~~r*~~l:~~r/~~l}for(M=/(\-?\d+)([\*\/])(\-?\d+)(?=[^\*\/]*$)/;M.test(s);s=s.replace(M,m));r=eval(s)
This solution would mean that people can enter ANY JavaScript code they want! The 303 character version does not execute any JavaScript; it only does math.