1

I have a basic Chrome App that I'm building that constructs strings like this:

"1 + 4 - 3 + -2"

Seeing as you can't use eval() in Chrome Apps, how can I get the answer to a string like so?

eg. If this was just a normal webpage I would use something like this:

var question = {
  text: "1 + 4 - 3 + -2",
  answer: eval(this.text)
}

Is there any possible way of replacing eval() with something else to answer a string like question.text?

Oliver
  • 1,576
  • 1
  • 17
  • 31
  • @JSelser A link, please? – Oliver Oct 07 '15 at 02:31
  • Here's a question which accepted answer has enough links to spin your head for days. The shunting yard algorithm is an automaton: http://stackoverflow.com/questions/114586/smart-design-of-a-math-parser – JSelser Oct 07 '15 at 03:31

2 Answers2

3

Try modifying string to

"+1 +4 -3 -2"

utilizing String.prototype.split() , Array.prototype.reduce() , Number()

var question = {
  text: "+1 +4 -3 -2",
  answer: function() {
            return this.text.split(" ")
                   .reduce(function(n, m) {
                     return Number(n) + Number(m)
                   })
          }
};

console.log(question.answer())
guest271314
  • 1
  • 15
  • 104
  • 177
  • Of course! Didn't think about using an array. I guess I could expand upon that method to support other kinds of math strings. Thanks. – Oliver Oct 07 '15 at 02:43
  • 1
    Brilliant solution. Seriously doubt you can expand it to support different operators though. – JSelser Oct 07 '15 at 03:14
0

Try this

var question = {
  text: "1 + 4 - 3 + -2",
  answer: eval(ans(question.text))
}
console.log('Text : '+question.text);
console.log('answer : '+question.answer);

Used String replace method

function ans(str){
var s = str.replace(/\s/g, '')
console.log('S : '+s);
return s;
}
Yash
  • 9,250
  • 2
  • 69
  • 74
  • That method simply removes whitespace and evaluates it using `eval`. What I'm asking for is a method to replace `eval` entirely. – Oliver Oct 07 '15 at 02:46
  • test the input "1 + 4 - 3 + -2" you given with above function it splits but the result is NAN. – Yash Oct 07 '15 at 02:57
  • If you mean the other answer, yes, but it can be changed to support the string I provided. The other answer isn't an in depth solution, as what I've asked for may prove difficult, but merely an idea for how to do it. – Oliver Oct 07 '15 at 03:00