Help updating eval()

Help updating eval()
0

#1

Hey all,

I’m trying to refactor some code while building my calculator and I need some help moving away from the eval() function. Here’s what I’ve got…

var calcResult = eval(calcValue); 
   return calcResult;}```

For example the ```calcValue``` would be ```3+3``` or ```5*10``` so my expectation is to return ```6``` or ```50```.

Things that I have tried but have not worked for me have been ```parseInt()``` and ```Number();``` among other stackoverflow Q&A's -- but I'm just not understanding.

Could someone help explain to me other alternatives? Maybe I'm missing something trying to use parseInt() and/or Number(); Any plugins I could use? Please let me know if there's anything else you need from me.

Honestly, I'm just looking for something simple that will evaluate but without actually using eval()..

<3

#2

Not sure if there is an easy way to do this. But what is the problem with eval()?


#3

Right @BenGitter … That’s what I’m seeing. Mostly because I was building this calculator as a Google Chrome Extension but eval() is not accepted by Google for security. So that sparked this whole idea to refactor & replace eval() but I haven’t been able to successfully figure it out yet.

Was hoping to get some insight from folks much better than me at this JavaScript stuff. I might just need to rebuild the JS functionality now that I know this — but was first looking for any alternatives.


#4

Just came across this solution:

function evil(fn) {
  return new Function('return ' + fn)();
}

evil('12/5*9+9.4*2'); // or whatever

Maybe that works to pass the “no-eval” rule.


#5
const OPERATIONS = {
  '+': (a, b) => a + b,
  '*': (a, b) => a * b,
  '/': (a, b) => a / b
}

function compute(stringToCompute, operations = OPERATIONS) {

  // '5+3' => ['5', '+', '3']
  const [firstNumAsString, operationSignature, secondNumAsString] = stringToCompute.split(/([+*/])/)
  
  // ['5', '3' ] => [5, 3]
  const [firstNum, secondNum] = [firstNumAsString, secondNumAsString].map(Number)  
  
  // '+' => a + b
  const operation = operations[operationSignature]
  
  return operation(firstNum, secondNum)
}

https://jsfiddle.net/tfzubopq/8/