All files / src/pages/flowsheet-page/economics/shared/model decimal.ts

80.95% Statements 17/21
63.63% Branches 7/11
100% Functions 0/0
88.23% Lines 15/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44          10x 10x 10x 10x 10x         10x         10x           62x       82x 82x 40x 40x 40x 40x             20x    
/**
 * Compares decimal strings without converting them to floating point, so
 * authoring checks preserve the precision accepted by the economics API.
 */
export function compareDecimalStrings(left: string, right: string) {
  const leftDecimal = parseDecimalString(left);
  const rightDecimal = parseDecimalString(right);
  Iif (!leftDecimal || !rightDecimal) return 0;
  const scale = Math.max(leftDecimal.scale, rightDecimal.scale);
  const leftValue = scaleDecimalValue(
    leftDecimal.value,
    leftDecimal.scale,
    scale,
  );
  const rightValue = scaleDecimalValue(
    rightDecimal.value,
    rightDecimal.scale,
    scale,
  );
  if (leftValue < rightValue) return -1;
  Iif (leftValue > rightValue) return 1;
  return 0;
}
 
export function isDecimalString(value: string) {
  return parseDecimalString(value) !== null;
}
 
function parseDecimalString(value: string) {
  const trimmed = value.trim();
  if (!/^-?\d+(\.\d+)?$/.test(trimmed)) return null;
  const negative = trimmed.startsWith("-");
  const unsigned = negative ? trimmed.slice(1) : trimmed;
  const [whole, fraction = ""] = unsigned.split(".");
  return {
    value: BigInt(`${negative ? "-" : ""}${whole}${fraction}`),
    scale: fraction.length,
  };
}
 
function scaleDecimalValue(value: bigint, fromScale: number, toScale: number) {
  return value * 10n ** BigInt(toScale - fromScale);
}