org.snapscript.tree.operation.Calculator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of snap-all Show documentation
Show all versions of snap-all Show documentation
Dynamic scripting for the JVM
package org.snapscript.tree.operation;
import java.util.ArrayList;
import java.util.List;
import org.snapscript.core.Evaluation;
import org.snapscript.tree.math.NumericOperator;
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 part : order) {
NumericOperator operator = part.getOperator();
if(operator != null) {
Evaluation right = variables.pop();
Evaluation left = variables.pop();
if(left != null && right != null) {
Evaluation evaluation = part.getEvaluation(left, right);
variables.push(evaluation);
}
} else {
Evaluation evaluation = part.getEvaluation(null, null);
if(evaluation != 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);
}
}
}