name:
src/main/java/io/protobase/f7/formulas/statistical/AVERAGE.java
-rw-r--r--
1392
1package io.protobase.f7.formulas.statistical;
2
3import io.protobase.f7.errors.DivException;
4import io.protobase.f7.formulas.AbstractFormula;
5import io.protobase.f7.formulas.FormulaName;
6import io.protobase.f7.models.GridColumnRowKey;
7import io.protobase.f7.utils.Converters;
8import io.protobase.f7.utils.Mappers;
9
10import java.util.Arrays;
11import java.util.List;
12import java.util.function.BiFunction;
13import java.util.function.Function;
14import java.util.stream.Collectors;
15
16public class AVERAGE extends AbstractFormula {
17 public static FormulaName NAME = FormulaName.AVERAGE;
18 public static AVERAGE SELF = new AVERAGE();
19
20 public AVERAGE() {
21 super();
22 }
23
24 public AVERAGE(Function<Object, Object> lookup, BiFunction<GridColumnRowKey, Object, Object> collateralLookup) {
25 super(lookup, collateralLookup);
26 }
27
28 @Override
29 public Object internal(GridColumnRowKey origin, Object... values) {
30 checkAtLeastLength(values.length, 1, NAME);
31 List<Double> numbers = Arrays.stream(values)
32 .map(lookup)
33 .flatMap(Mappers::toFlatStream)
34 .map(Converters::toDouble)
35 .collect(Collectors.toList());
36 if (numbers.size() == 0) {
37 return new DivException("Formula AVERAGE caused an error when attempting to divide by zero.");
38 }
39 double sum = 0;
40 for (Double number : numbers) {
41 sum += number;
42 }
43 return sum / numbers.size();
44 }
45}