From f26df219c0bb236740abf711b7b4de05f8c3fc2f Mon Sep 17 00:00:00 2001 From: AbhaySingh2477 Date: Wed, 24 Jun 2026 14:02:27 +0530 Subject: [PATCH] Fix infinite loop and parsing error on subtraction --- CalculatorLexer.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/CalculatorLexer.js b/CalculatorLexer.js index 9ade9b5..3b2e21d 100644 --- a/CalculatorLexer.js +++ b/CalculatorLexer.js @@ -32,10 +32,18 @@ CalculatorLexer.prototype.nextToken = function () { return '*'; } } else if (this.c === '-') { - if (this.isNumber(this.input[this.p + 1])) { + var isNegativeSign = false; + var i = this.p - 1; + while (i >= 0 && /\s/.test(this.input[i])) i--; + if (i < 0 || ['(', '+', '-', '*', '/', '=', ','].indexOf(this.input[i]) > -1) { + isNegativeSign = true; + } + + if (isNegativeSign && this.isNumber(this.input[this.p + 1])) { // this is a negative number return this.number(); } else { + this.consume(); return '-'; } } else if (this.isNumber(this.c)) {