Skip to content

Instantly share code, notes, and snippets.

@dmi3y
Created August 3, 2015 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmi3y/824a64d25eb3946016a1 to your computer and use it in GitHub Desktop.
Save dmi3y/824a64d25eb3946016a1 to your computer and use it in GitHub Desktop.
function calcFromStr(str) {
var ops = ['*','/','+','-'];
var reg = /(\b\D)/;
var calc = str.split(reg);
function calculator(l, op, r) {
switch( op ) {
case '*':
return l*r;
case '/':
return l/r;
case '+':
return l+r;
case '-':
return l-r;
}
}
calc.forEach(function(el, ix) {
if ( ix % 2 === 0 ) {
calc[ix] = Number(el);
}
});
do {
var op = ops.shift();
var ix;
var nval;
do {
ix = calc.indexOf(op);
if ( ix > 0 ) {
nval = calculator(calc[ix - 1], op, calc[ix + 1]);
calc.splice(ix-1, 3, nval);
}
} while ( ix > -1 );
} while( ops.length );
return calc[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment