0

I am making a four function calculator with javascript. I am storing the button presses in an array 'tmp', removing operators from the beginning and end of the array, converting to a string, and removing commas.

Any given string should be properly formatted for calculation except for the fact that it's in a string. What's the best way to get it out of the string and calculated?

thanks!

  • So if your input is `"-4*2"` you're doing `4*2` ? Is that a good idea? Also if you have say this input: `"-1+2*2/"` and you get this array: `["1", "+", "2", "*", "2"]` what's your expected result? – Roko C. Buljan May 25 '18 at 21:54
  • regex's with capture groups. – JGFMK May 25 '18 at 22:00
  • @RokoC.Buljan [-,4,*,2] turns out to be "-4*2". /[+*/]/g is my regex for that. ["1", "+", "2", "*", "2"] should return 5, as per pemdas. Although, I could iterate from left to right if I wanted. – Morgan Galvin May 25 '18 at 22:04

1 Answers1

0

You can do something like this:

// Array of inputs in you calculator
const inputs = ["1", "+", "2", "*", "2"];

// inputs.join(" ") turns the array into "1 + 2 * 2" string
// and the fn() returns the result
const fn = new Function("return " + inputs.join(" "));

console.log(fn()); // 5
user3210641
  • 1,565
  • 1
  • 10
  • 14