From 9cef8dbc799343f6fc0fca926fbef4917b94f335 Mon Sep 17 00:00:00 2001 From: NeonXP Date: Fri, 6 Sep 2013 08:19:02 +0400 Subject: + Added cache, which speeds up the repetitive calculations + Returned variables, because they need for cached expressions --- src/NXP/Classes/Calculator.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'src/NXP/Classes/Calculator.php') diff --git a/src/NXP/Classes/Calculator.php b/src/NXP/Classes/Calculator.php index e74b7ab..41e0d9f 100644 --- a/src/NXP/Classes/Calculator.php +++ b/src/NXP/Classes/Calculator.php @@ -13,7 +13,9 @@ namespace NXP\Classes; use NXP\Classes\Token\InterfaceOperator; use NXP\Classes\Token\TokenFunction; use NXP\Classes\Token\TokenNumber; +use NXP\Classes\Token\TokenVariable; use NXP\Exception\IncorrectExpressionException; +use NXP\Exception\UnknownVariableException; /** * @author Alexander Kiryukhin @@ -21,17 +23,28 @@ use NXP\Exception\IncorrectExpressionException; class Calculator { /** - * @param array $tokens Tokens in reverse polish notation - * @return number + * Calculate array of tokens in reverse polish notation + * @param array $tokens Array of tokens + * @param array $variables Array of variables + * @return number Result * @throws \NXP\Exception\IncorrectExpressionException + * @throws \NXP\Exception\UnknownVariableException */ - public function calculate($tokens) + public function calculate($tokens, $variables) { $stack = array(); foreach ($tokens as $token) { if ($token instanceof TokenNumber) { array_push($stack, $token); } + if ($token instanceof TokenVariable) { + $variable = $token->getValue(); + if (!array_key_exists($variable, $variables)) { + throw new UnknownVariableException(); + } + $value = $variables[$variable]; + array_push($stack, new TokenNumber($value)); + } if ($token instanceof InterfaceOperator || $token instanceof TokenFunction) { array_push($stack, $token->execute($stack)); } -- cgit v1.2.3