jiggzson / nerdamer

a symbolic math expression evaluator for javascript
http://www.nerdamer.com
MIT License
517 stars 82 forks source link

Some invalidly formatted equations return an empty string instead of throwing error. #440

Closed Saikedo closed 5 years ago

Saikedo commented 5 years ago

nerdamer("5+") returns an undefined instead of throwing an error.

something like nerdamer("(5") throws an error saying "Missing closed bracket for bracket at 1".

I find the 2nd approach to be better because it allows us to see what was wrong and this allows us to notify the user about the mistake done in their input.

Is there a reason why the first example that I presented does not throw an error?

jiggzson commented 5 years ago

@Saikedo, this is a bug but fortunately it's easily remedied. You can quickly perform check when processing the stack and if the RH value is undefined you can throw an error. No need to check LH values since this check was already performed when generating the RPN. Just add the snippet below right after this line.

//Throw an error if the RH value is empty. This cannot be a postfix since we already checked
if(typeof a === 'undefined') 
    throw new OperatorError(e+' is not a valid postfix operator at '+e.column);

The end result should look the code below

var b = Q.pop();
var a = Q.pop();
//Throw an error if the RH value is empty. This cannot be a postfix since we already checked
if(typeof a === 'undefined') 
    throw new OperatorError(e+' is not a valid postfix operator at '+e.column);

Q.push(_[e.action](a, b));

Although this solution is a perfectly good long-term solution, for maintainability purposes it would be better to catch this error earlier. I'll leave this issue open and I'll add this fix at a later date when have some time. Let me know if this works for you.