Commits

Christophe Furmaniak committed 66bb1e6

untested first version of RPNEvaluator.evaluate

Comments (0)

Files changed (1)

src/main/java/net/awl/acacia/tagresolver/RPNEvaluator.java

 package net.awl.acacia.tagresolver;
 
+import java.util.ArrayDeque;
 import java.util.Deque;
 
 /**
  * Time: 20:25
  */
 public class RPNEvaluator {
+    /**
+     * Inspiration: http://finandsys.com/finandsys-blog/index.php?tag/Algorithme
+     *
+     * @param tokens
+     * @return
+     */
     public GroupOfServers evaluate(Deque<Token> tokens) {
-        return null;
+        Deque<Token> evaluationDeque = new ArrayDeque<Token>();
+        for (Token token : tokens) {
+            if (token.isGroupOfServers()) {
+                evaluationDeque.push(token);
+            } else {
+                Operation operation = token.getOperation();
+                if (evaluationDeque.size() < operation.getNbOfArgs()) {
+                    throw new IllegalArgumentException("The input Deque is not a valid RPN definition, there should be at least <" + operation.getNbOfArgs() + "> operand(s) left in the evaluation deque (size=" + evaluationDeque.size() + ")");
+                }
+                GroupOfServers[] operands = new GroupOfServers[operation.getNbOfArgs()];
+                for (int i = 0; i < operation.getNbOfArgs(); i++) {
+                    operands[i] = evaluationDeque.pop().getGroupOfServers();
+                }
+                evaluationDeque.push(Token.fromGroupOfServers(operation.execute(operands)));
+            }
+        }
+        if (evaluationDeque.size() == 1) {
+            return evaluationDeque.pop().getGroupOfServers();
+        } else {
+            throw new IllegalArgumentException("The input Deque is not a valid RPN definition, there are more (" + evaluationDeque.size() + ") than 1 element left in the evaluation deque and no more operations");
+        }
+
     }
 }