Tell us what’s happening:
I’m building JavaScript calculator project. But I found an issue.
For example, If you type 3 + 5 * 6 - 2 / 4 on calculator buttons you will see on the console:
"3+5*6-2/4"
So I want to convert this string from "3+5*6-2/4" to "32.5".
How to do that?
Link to the project link:
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0
My recommendation is not to create a string and then parse it (which you can do). If you store the values of numbers and symbols into a data structure, then you can use that data structure both to create the string and perform logic.
Hi, there! You can’t do that on a string. You need to separate numbers and symbols, and do the math depending the symbol,.and then return a string if you want to.
So the calculator can operate in one of two ways, but both ways would give a different answer to this. The first and easiest is left-to-right, simply performing each operation as you encounter it. The second is order of operations, and is much the way math is taught - parentheses, then exponents, then multiplication/division, then addition/subtraction.
Here’s the thing: in both cases, the pattern is much the same. Extract a particular operator and the values to it’s left and right, collapse those three into a single value, then re-insert that value where the original three were extracted.
For left-to-right, this is easy - grab the first operator and its adjacent numbers, evaluate it, and insert the value, creating a new “adjacent” value for the next operator.
For order of operations, you face the additional challenge of locating the next operator on which to act. Which can be anywhere in the string.
I found strings to be less then ideal For this, as evaluating like this was too much like work, and I’m too much like lazy. Instead, i used an array, and each time an operator is added, i push the preceding number on, followed by the operator. Thus, collapsing the array becomes finding the operator in the array, evaluating the numbers adjacent to it, and splicing the resultant value in (collapsing three values into one).
Sounds to me like, before you begin coding this, you might want to map out logic. It its pretty common to write out some “pseudocode” your own words describing the logic and flow. Less about the “how do i make this happen,” and more a high-level “what do i want to happen.”
Doing this makes the actual coding somewhat easier.