From b95ab24f367baf928332dc5040ab444c1c719623 Mon Sep 17 00:00:00 2001 From: Bruce Wells Date: Tue, 19 May 2020 22:36:55 -0400 Subject: setDivisionByZeroIsZero --- src/NXP/MathExecutor.php | 16 ++++++++++++++++ tests/MathTest.php | 9 ++------- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/NXP/MathExecutor.php b/src/NXP/MathExecutor.php index 0b7e9db..e214209 100644 --- a/src/NXP/MathExecutor.php +++ b/src/NXP/MathExecutor.php @@ -468,6 +468,22 @@ class MathExecutor return $this->tokenFactory->getFunctions(); } + /** + * Set division by zero returns zero instead of throwing DivisionByZeroException + * + * @return MathExecutor + */ + public function setDivisionByZeroIsZero() : self + { + $this->addOperator(new Operator("/", false, 180, function ($a, $b) { + if ($b == 0) { + return 0; + } + return $a / $b; + })); + return $this; + } + public function __clone() { $this->addDefaults(); diff --git a/tests/MathTest.php b/tests/MathTest.php index 958f14c..39ac649 100644 --- a/tests/MathTest.php +++ b/tests/MathTest.php @@ -203,7 +203,7 @@ class MathTest extends TestCase ['(-3 * -1)'], ['1 + (-3 * -1)'], ['1 + ( -3 * 1)'], - ['1 + (3 * -1)'], + ['1 + (3 *-1)'], ['1 - 0'], ['1-0'], ]; @@ -226,12 +226,7 @@ class MathTest extends TestCase public function testZeroDivision() { $calculator = new MathExecutor(); - $calculator->addOperator(new Operator("/", false, 180, function ($a, $b) { - if ($b == 0) { - return 0; - } - return $a / $b; - })); + $calculator->setDivisionByZeroIsZero(); $this->assertEquals(0, $calculator->execute('10 / 0')); } -- cgit v1.2.3