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/js/formulas/statistical/AVERAGEA.ts
-rw-r--r--
1719
 1import { isNotNull } from "../../utils/Other";
 2import { DivException } from "../../errors/DivException";
 3import { SheetColumnRowKey } from "../../models/common/SheetColumnRowKey";
 4import { Complex } from "../../models/common/Types";
 5import { Converters } from "../../utils/Converters";
 6import { Counter } from "../../utils/Counter";
 7import { Mappers } from "../../utils/Mappers";
 8import { Reducers } from "../../utils/Reducers";
 9import { AbstractFormula } from "../AbstractFormula";
10import { FormulaName } from "../FormulaName";
11
12export class AVERAGEA extends AbstractFormula {
13  static SELF: AVERAGEA = new AVERAGEA();
14  NAME = FormulaName.AVERAGEA;
15
16  internal(origin: SheetColumnRowKey, ...values: Array<Complex>) {
17    AbstractFormula.checkAtLeastLength(values.length, 1, this.NAME);
18    const counter = new Counter<number>();
19    const sum = values
20      .map(this.lookup)
21      .map(Mappers.flattenGridsToArrays) // 1, "2", [null, 1, "99", "Text.", null, #REF!, true]
22      .map(Mappers.coerceNonArrayValuesToNumberOrThrow) // 1, 2, [null, 1, "99", "Text.", null, #REF!, true]
23      .map(Mappers.ensureAllAreArrays) // [1], [2], [null, 1, "99", "Text.", null, #REF!, true]
24      .reduce(Reducers.join) // [1, 2, null, 1, "99", "Text.", null, #REF!, true]
25      .filter(isNotNull) // [1, 2, 1, "99", "Text.", #REF!, true]
26      .map(Converters.textToZero) // [1, 2, 1, 0, 0, true]
27      .map(Converters.toNumber) // [1, 2, 1, 0, 0, 1]
28      .map((value) => counter.count(value))
29      .reduce(Reducers.sum, 0);
30    if (counter.getCount() === 0) {
31      return new DivException(
32        "Formula AVERAGEA caused an error when attempting to divide by zero."
33      );
34    }
35    return sum / counter.getCount();
36  }
37}