diff options
-rw-r--r-- | src/NXP/MathExecutor.php | 31 | ||||
-rw-r--r-- | tests/MathTest.php | 24 |
2 files changed, 50 insertions, 5 deletions
diff --git a/src/NXP/MathExecutor.php b/src/NXP/MathExecutor.php index 1debc50..ca27539 100644 --- a/src/NXP/MathExecutor.php +++ b/src/NXP/MathExecutor.php @@ -412,22 +412,26 @@ class MathExecutor /** * Execute expression * - * @param $expression + * @param string $expression + * @param bool $cache * @return number - * @throws Exception\IncorrectExpressionException * @throws Exception\IncorrectBracketsException + * @throws Exception\IncorrectExpressionException * @throws Exception\UnknownOperatorException - * @throws Exception\UnknownVariableException + * @throws UnknownVariableException */ - public function execute(string $expression) + public function execute(string $expression, bool $cache = true) { $cachekey = $expression; if (!array_key_exists($cachekey, $this->cache)) { $tokens = (new Tokenizer($expression, $this->operators))->tokenize()->buildReversePolishNotation(); - $this->cache[$cachekey] = $tokens; + if ($cache) { + $this->cache[$cachekey] = $tokens; + } } else { $tokens = $this->cache[$cachekey]; } + $calculator = new Calculator($this->functions, $this->operators); return $calculator->calculate($tokens, $this->variables, $this->onVarNotFound); } @@ -596,6 +600,23 @@ class MathExecutor return $this; } + /** + * Get cache array with tokens + * @return array + */ + public function getCache() : array + { + return $this->cache; + } + + /** + * Clear token's cache + */ + public function clearCache() : void + { + $this->cache = []; + } + public function __clone() { $this->addDefaults(); diff --git a/tests/MathTest.php b/tests/MathTest.php index 1e5da5a..a5061ad 100644 --- a/tests/MathTest.php +++ b/tests/MathTest.php @@ -589,4 +589,28 @@ class MathTest extends TestCase ]; } + public function testCache() + { + $calculator = new MathExecutor(); + $this->assertEquals(256, $calculator->execute('2 ^ 8')); // second arg $cache is true by default + + $this->assertIsArray($calculator->getCache()); + $this->assertEquals(1, count($calculator->getCache())); + + $this->assertEquals(512, $calculator->execute('2 ^ 9', true)); + $this->assertEquals(2, count($calculator->getCache())); + + $this->assertEquals(1024, $calculator->execute('2 ^ 10', false)); + $this->assertEquals(2, count($calculator->getCache())); + + $calculator->clearCache(); + $this->assertIsArray($calculator->getCache()); + $this->assertEquals(0, count($calculator->getCache())); + + $this->assertEquals(2048, $calculator->execute('2 ^ 11', false)); + $this->assertEquals(0, count($calculator->getCache())); + + + } + }
\ No newline at end of file |