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