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!

3
  • 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? Commented May 25, 2018 at 21:54
  • regex's with capture groups. Commented May 25, 2018 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. Commented May 25, 2018 at 22:04

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

With considerations to this answers
Not sure I should give any credits when I thought of this on my own ...
I'm sure you did. Rephrased my comment.
That got me where I needed to go. Thank you much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.