]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.spreadsheet/src/org/simantics/spreadsheet/solver/formula/AverageFormulaFunction.java
Adopt spreadsheet changes made in Balas development
[simantics/platform.git] / bundles / org.simantics.spreadsheet / src / org / simantics / spreadsheet / solver / formula / AverageFormulaFunction.java
1 package org.simantics.spreadsheet.solver.formula;
2
3 import org.simantics.databoard.binding.mutable.Variant;
4 import org.simantics.spreadsheet.SpreadsheetMatrix;
5 import org.simantics.spreadsheet.Spreadsheets;
6 import org.simantics.spreadsheet.solver.formula.parser.ast.AstArgList;
7 import org.simantics.spreadsheet.solver.formula.parser.ast.AstValue;
8
9 public class AverageFormulaFunction implements CellFormulaFunction<Object> {
10
11     @Override
12     public Object evaluate(CellValueVisitor visitor, AstArgList args) {
13         if (args.values.size() == 0)
14             throw new IllegalStateException();
15         Double sum = 0.0;
16         double count = 0.0;
17         for(AstValue value : args.values){
18             Object res = value.accept(visitor);
19             if (res instanceof SpreadsheetMatrix) {
20                 Object value2 = ((SpreadsheetMatrix) res).sumWithFormulaError();
21                 if(value2 instanceof String) return value2;
22
23                 sum += ((Number)value2).doubleValue();
24                 count += ((SpreadsheetMatrix) res).countOfActualDoubleValues();
25             } else {
26                 FormulaError2 err = FormulaError2.forObject(res);
27                 if(err!=null) return err.getString();
28
29                 if(res instanceof Variant){
30                     Double dVal = Spreadsheets.asDoubleWhereEmptyStringIsZero(res);
31                     if(dVal==null) res = ((Variant)res).toString();
32                     else res = dVal;
33                 }
34
35                 Double v = null;
36                 if(res instanceof String && !res.equals("")){
37                     v = Spreadsheets.asDoubleWhereEmptyStringIsZero(res);
38                 }
39                 else if(res instanceof Number)
40                     v = Spreadsheets.asDoubleWhereEmptyStringIsZero(res);
41
42                 if(v!=null){
43                     sum += v;
44                     count++;
45                 }
46             }
47         }
48         if(count==0.0) return FormulaError2.DIV0.getString();
49         return sum/count;
50     }
51 }