Created
August 3, 2015 10:06
-
-
Save dmi3y/824a64d25eb3946016a1 to your computer and use it in GitHub Desktop.
Revisions
-
dmi3y created this gist
Aug 3, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,50 @@ 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]; }