name:
src/main/js/formulas/engineering/BIN2DEC.ts
-rw-r--r--
1255
1import { NumException } from "../../errors/NumException";
2import { ValueException } from "../../errors/ValueException";
3import { SheetColumnRowKey } from "../../models/common/SheetColumnRowKey";
4import { Complex } from "../../models/common/Types";
5import { Converters } from "../../utils/Converters";
6import { AbstractFormula } from "../AbstractFormula";
7import { FormulaName } from "../FormulaName";
8
9export class BIN2DEC extends AbstractFormula {
10 static SELF: BIN2DEC = new BIN2DEC();
11 NAME = FormulaName.BIN2DEC;
12
13 internal(origin: SheetColumnRowKey, ...values: Array<Complex>) {
14 AbstractFormula.checkLength(values.length, 1, this.NAME);
15 const first = Converters.first(this.collateralLookup(origin, values[0]));
16 if (typeof first === "boolean") {
17 throw new ValueException(
18 `Function BIN2DEC parameter 1 expects text values. But '${first}' is a boolean and cannot be coerced to a text.`
19 );
20 }
21 const n = Converters.toText(first);
22 if (!/^[01]{1,10}$/.test(n)) {
23 throw new NumException(`Input for BIN2DEC ('${n}') is not a valid binary representation.`);
24 }
25 if (n.length === 10 && n.substring(0, 1) === "1") {
26 return parseInt(n.substring(1), 2) - 512;
27 }
28 return parseInt(n, 2);
29 }
30}