If I have several Elements each containing a number, and there are different arithmetic operations between them, How can I extract the final result ?!!
[ I thought I should store the numbers in an array with their arithmetic operations by the attributes of each arithmetic, then I didn’t know what to do next ]
I understand the appeal of building something from scratch yourself, so if you’re looking to implement this without a third-party library, here are some suggestions.
The way I would do it is to store the math operations in an object which properties are the operators so you can call the operations doing something like mathObj['/']
Once you have an object that stores all the operations you want to support, you can extract the numbers and operators from the string, then use the numbers as arguments to the methods you call using the operators you just extracted. For your example, that would be something like:
That means; evaluate 5 and 7 using the division operation with property name '/' inside mathObj, do the same with 11 and 4, then evaluate the results using the '+' operation inside mathObj.
Of course, you’re going to want to consider order of operations as well, so you might need to introduce a process that parses each operator in relation to the position they appear in, their order of precedence in PEMDAS and the order of the numbers.
If you go with an array, methods like map and filter might be useful here.
You are creating global variable in this line: let = calculation = [“fa-plus”, “fa-divide”, “fa-xmark”, “fa-minus”];
I suggest to use Strict Mode to avoid such mistakes.
While forming an expression that user will see, you can also create a simple string holding that expression. It’s sample value would be “6/2+3*1”.
Then you can easily find out the solution by using function constructor: new Function("return " + expression).call(null);