Created
August 3, 2015 10:06
-
-
Save dmi3y/824a64d25eb3946016a1 to your computer and use it in GitHub Desktop.
Basic calculator http://jsbin.com/nowela/edit?html,js
This file contains 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 characters
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