f7
f7 is a spreadsheet formula execution library
git clone https://git.vogt.world/f7.git
Log | Files | README.md | LICENSE.md
← All files
name: src/main/java/io/protobase/f7/formulas/statistical/AVERAGEA.java
-rw-r--r--
1416
 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 AVERAGEA extends AbstractFormula {
17  public static FormulaName NAME = FormulaName.AVERAGEA;
18  public static AVERAGEA SELF = new AVERAGEA();
19
20  public AVERAGEA() {
21    super();
22  }
23
24  public AVERAGEA(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::toFlatStreamFilterOnlyNumeric)
34        .map(Converters::toDouble)
35        .collect(Collectors.toList());
36    if (numbers.size() == 0) {
37      return new DivException("Formula AVERAGEA 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}