Let me just start by saying I know using eval() is considered bad practice, but I'm using it on an application that's purely client-based, so no DBs and backends. I'm using it just for evaluating mathematical expressions.
Say I have this string which has been stripped from spaces from the beginning: "1-(2-3)". If you call eval() with it you get eval("1-(2-3)") == 1-(-1) == 2.
But here's the catch. For some complex reasons (which are irrelevant to this question), I have to evaluate the parenthesis first and replace the parenthesis with its evaluated value. So I will get the string "1--1". But if I call eval like this: eval("1--1"), it will interpret -- as an decrement operation and I get the error
Uncaught SyntaxError: Invalid left-hand side expression in postfix operation
For example,
const input = "1-(2-3)"
const str = input.replace("(2-3)", eval("(2-3)"))
console.log(str) // "1--1"
const result = eval(str) // Here things go wrong. Eval parses `--` as the decrement operator.
console.log(result)
I know this isn't a fault of eval, it's meant to evaluate general code, not just mathematical expressions, but how can I get around this?
another option is you can just wrap eval in
let str = input.replace("(2-3)", eval("(2-3)")) with parenthesis to make it let str = input.replace("(2-3)", "(${eval("(2-3)")})"). That would be the quickest workaround fort this particular problem. But different ones may arise.
As Sharjeel mentioned, BODMAS is important, but another hint is:
You can look into Reverse Polish Notation as this way of taking down complex equations is the way computers think basically. It will help you understand how to properly calculate longer expressions and will make your mechanism ready for different problems you may face with current version
Actually, I thought about it and the simplest solution is probably just using String.prototype.replaceAll() to replace all occurrences of -- to - -.
const input = "1-(2-3)"
let str = input.replace("(2-3)", eval("(2-3)"))
console.log(str) // "1--1"
str = str.replaceAll('--', '- -')
const result = eval(str)
console.log(result) // 2
You could pad with space for every nested expression before you add the value to the outer string.
x = '-1';
r = eval('1-' + ` ${x} `);