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/math/DIVIDE.java
-rw-r--r--
1475
 1package io.protobase.f7.formulas.math;
 2
 3import io.protobase.f7.errors.DivException;
 4import io.protobase.f7.errors.F7Exception;
 5import io.protobase.f7.formulas.AbstractFormula;
 6import io.protobase.f7.formulas.FormulaName;
 7import io.protobase.f7.models.GridColumnRowKey;
 8import io.protobase.f7.utils.Converters;
 9
10import java.util.function.BiFunction;
11import java.util.function.Function;
12
13public class DIVIDE extends AbstractFormula {
14  public static FormulaName NAME = FormulaName.DIVIDE;
15  public static DIVIDE SELF = new DIVIDE();
16
17  public DIVIDE() {
18    super();
19  }
20
21  public DIVIDE(Function<Object, Object> lookup, BiFunction<GridColumnRowKey, Object, Object> collateralLookup) {
22    super(lookup, collateralLookup);
23  }
24
25  @Override
26  public Object internal(GridColumnRowKey origin, Object... values) {
27    checkLength(values.length, 2, NAME);
28    Object first = Converters.first(collateralLookup.apply(origin, Converters.first(values[0])));
29    Object second = Converters.first(collateralLookup.apply(origin, Converters.first(values[1])));
30    if (first instanceof F7Exception) {
31      return first;
32    }
33    if (second instanceof F7Exception) {
34      return second;
35    }
36    return this.divide(Converters.toDouble(first), Converters.toDouble(second));
37  }
38
39  private Double divide(Double dividend, Double divisor) {
40    if (divisor.equals(0.0)) {
41      throw new DivException("Formula DIVIDE parameter 2 cannot be zero.");
42    }
43    return dividend / divisor;
44  }
45}