All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.snapscript.tree.operation.Calculator Maven / Gradle / Ivy


package org.snapscript.tree.operation;

import java.util.ArrayList;
import java.util.List;

import org.snapscript.core.Evaluation;

public class Calculator {
   
   private final CalculatorStack tokens;
   private final CalculatorStack variables;      
   private final List order;
   
   public Calculator() {
      this.tokens = new CalculatorStack();      
      this.variables = new CalculatorStack();
      this.order = new ArrayList();
   }
   
   public Evaluation create(){
      while(!tokens.isEmpty()) {
         CalculationPart top = tokens.pop();
         
         if(top != null) {
            order.add(top);
         }
      }      
      for(CalculationPart token : order) {
         NumericOperator operator = token.getOperator();
   
         if(operator != null) {
            Evaluation right = variables.pop();
            Evaluation left = variables.pop();
            
            if(left != null && right != null) {             
               Evaluation evaluation = new CalculationOperation(operator, left, right);
               
               variables.push(evaluation);
            }                          
         } else {
            Evaluation evaluation = token.getEvaluation();
            
            if(token != null) {
               variables.push(evaluation);
            }
         }               
      }
      return variables.pop();
   }
   
   public void update(CalculationPart part) {
      NumericOperator operator = part.getOperator();
      
      if(operator != null) {
         while(!tokens.isEmpty()) {
            CalculationPart top = tokens.pop();
            NumericOperator other = top.getOperator();
                                 
            if(other.priority < operator.priority) {
               tokens.push(top);
               break;
            } else {
               order.add(top);
            }            
         }
         tokens.push(part);
      } else {
         order.add(part);
      }
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy