How can I do that!

If I have several Elements each containing a number, and there are different arithmetic operations between them, How can I extract the final result ?!!

Ex :

[ 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 ]

Link : https://codepen.io/someone_49/pen/GROYLBe

I would be grateful for any help😊

Take a look at https://mathjs.org/

2 Likes

Hey Albaraa, cool project you have there.

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['/']

Have a read through Working with Objects if you need a refresher.

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:

mathObj['+'](mathObj['/'](5, 7), mathObj['/'](11, 4))

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.

Good luck and have fun building!

2 Likes

Thank you so much…

This is exactly what I want…:blush:

But I ran into some problems :

1-

2-

I didn’t quite know how to do it, Can I get a hint or explanation in another way🤗

It’s really cool, thank you very much

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);

It’s the easiest solution, because you don’t need to worry about order of operations. You can read more about function constructor in here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function