aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
l---------bin/phpunit1
-rw-r--r--src/NXP/Classes/Lexer.php16
-rw-r--r--src/NXP/Classes/Token/TokenMinus.php8
-rw-r--r--tests/MathTest.php14
4 files changed, 34 insertions, 5 deletions
diff --git a/bin/phpunit b/bin/phpunit
deleted file mode 120000
index 4ba3256..0000000
--- a/bin/phpunit
+++ /dev/null
@@ -1 +0,0 @@
-../vendor/phpunit/phpunit/phpunit \ No newline at end of file
diff --git a/src/NXP/Classes/Lexer.php b/src/NXP/Classes/Lexer.php
index 73c25ac..cd12d21 100644
--- a/src/NXP/Classes/Lexer.php
+++ b/src/NXP/Classes/Lexer.php
@@ -78,8 +78,8 @@ class Lexer
// if the number starts with a minus sign, it could be a negative number, or it could be an operator grabbed by the greedy regex
// if previous token is an operator, then it negative, otherwise remove the minus sign and put a negative operator on the stack
if ($lastToken !== null) {
- $value = (int)$token->getValue();
- if ($value < 0 && ! ($lastToken instanceof AbstractOperator)) {
+ $value = $token->getValue();
+ if (($value < 0 || $this->isNegativeZero($value)) && ! ($lastToken instanceof AbstractOperator)) {
$token = new TokenNumber(abs($value));
$output[] = $token;
$output[] = new TokenMinus('-');
@@ -145,4 +145,16 @@ class Lexer
return $output;
}
+
+ /**
+ * Check if the value is a negative zero
+ *
+ * @param int|float $x The value to check
+ * @return boolean True if negative zero, false otherwise
+ */
+ private function isNegativeZero($x)
+ {
+ $floatVal = floatval($x);
+ return $floatVal === 0.0 && $floatVal ** -1 === -INF;
+ }
}
diff --git a/src/NXP/Classes/Token/TokenMinus.php b/src/NXP/Classes/Token/TokenMinus.php
index d8ac079..b4b04e3 100644
--- a/src/NXP/Classes/Token/TokenMinus.php
+++ b/src/NXP/Classes/Token/TokenMinus.php
@@ -53,8 +53,12 @@ class TokenMinus extends AbstractOperator
$op2 = array_pop($stack);
$op1 = array_pop($stack);
- if ($op1 === null || $op2 === null) {
- throw new IncorrectExpressionException("Subtraction requires two operators");
+ if ($op2 === null) {
+ throw new IncorrectExpressionException("Subtraction requires right operator");
+ }
+
+ if (!$op1) {
+ $op1 = new TokenNumber(0);
}
$result = $op1->getValue() - $op2->getValue();
diff --git a/tests/MathTest.php b/tests/MathTest.php
index 391408e..0de2465 100644
--- a/tests/MathTest.php
+++ b/tests/MathTest.php
@@ -297,4 +297,18 @@ class MathTest extends \PHPUnit\Framework\TestCase
$calculator->execute('test("' . $testString . '")'); // single quotes
$calculator->execute("test('" . $testString . "')"); // double quotes
}
+
+ public function testBeginWithBracketAndMinus()
+ {
+ $calculator = new MathExecutor();
+ $this->assertEquals(-4, $calculator->execute('(-4)'));
+ $this->assertEquals(1, $calculator->execute('(-4 + 5)'));
+ }
+
+ public function testMinusZero()
+ {
+ $calculator = new MathExecutor();
+ $this->assertEquals(1, $calculator->execute('1 - 0'));
+ $this->assertEquals(1, $calculator->execute('1-0'));
+ }
}