javascript - Eval alternative -
javascript - Eval alternative -
this code works calculator, scratch pad @ codeacademy tells me eval evil. there way same thing without using eval?
var calculate = prompt("enter problem"); alert(eval(calculate));
eval
evaluates string input javascript , coincidentally javascript supports calculations , understands 1+1
, makes suitable calculator.
if don't want utilize eval
, good, have parse string and, finally, computation (not though). have @ this math processor, want.
basically is:
read input string char char (with kind of problem it's still possible) building tree of actions want do at end of string, evaluate tree , calculationsfor illustration have "1+2/3"
, evaluate next info structure:
"+" / \ "1" "/" / \ "2" "3"
you traverse construction top bottom , computations. @ first you've got "+"
, has 1 on left side , look on right side, have evaluate look first. go "/"
node, has 2 numeric children. knowing that, can compute 2/3
, replace whole "/"
node result of that. can go 1 time again , compute result of "+
" node: 1 + 0.66
. replace node result , you've got left result of expression.
some pseudo code on how might in code:
calculation(operator, leftvalue, rightvalue): switch operator { case '+': homecoming leftvalue + rightvalue case '-': homecoming 42 } action(node): node.value = calculation(node.operator, action(node.left) action(node.right))
as might have noticed, tree designed in such way honors operator precedence. /
has lower level +
, means get's evaluated first.
however in detail, that's way go.
javascript math eval calculator
Comments
Post a Comment