silentmatt / expr-eval

Mathematical expression evaluator in JavaScript
http://silentmatt.com/javascript-expression-evaluator/
MIT License
1.18k stars 239 forks source link

Using expr-eval on CodePen? #232

Closed DragonOsman closed 3 years ago

DragonOsman commented 3 years ago

I want to build a calculator app on CodePen for a FreeCodeCamp project challenge. Is it possible to use expr-eval on CodePen? And if so, how? Thanks in advance for any help.

silentmatt commented 3 years ago

Yes, you can import the library from cdnjs. If you open the settings for the CodePen, and change to the JS section, there's a search box under "Add External Scripts/Pens". Type "expr-eval" and it should come up. Or you can copy+paste the URL (https://cdnjs.cloudflare.com/ajax/libs/expr-eval/2.0.2/bundle.min.js for the most recent version) directly into one of the text boxes.

It'll make the Parser class available under the exprEval "namespace", so you can use it like this:

var parser = new exprEval.Parser();
console.log(parser.parse('6*x').evaluate({ x: 7 }));
DragonOsman commented 3 years ago

Thanks for the reply and help. I'll do that, then.

silentmatt commented 3 years ago

No problem. I'll close this, but feel free to re-open or open a new issue if you have problems or other questions.

DragonOsman commented 3 years ago

I do have another question about this.

What I want to do is build a calculator by following the specs mentioned here. So my question is: is it possible to do this using this library for the calculation string parsing and evaluation? It also says:

User Story #13: If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign). For example, if `5 + * 7` = is entered, the result should be `35` (i.e. 5 * 7); if 5 * - 5 = is entered, the result should be -25 (i.e. 5 x (-5)).

I'll be able to use this library for this, too, right? Probably will have to write my own function, but yeah.

silentmatt commented 3 years ago

It won't be able to handle that directly, but you might be able to either pre-process the input to remove the extra operator before you evaluate it, or not append it in the first place if you're generating the string.

The way the parser's written, there probably isn't a good way to modify it to support that "natively" so you'll almost definitely need to do some kind of pre-processing.

DragonOsman commented 3 years ago

I don't have to completely ignore it, I actually need to use the operator given most recently. And if I have something like "4 + - 5", it'll be treated as "4 + (-5)", probably. Or "4 - 5" -> "4 -5". Aside from that, when given consecutive operators, it has to take only the most recent one.