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

87.5% Statements 21/24
25% Branches 1/4
100% Functions 3/3
100% Lines 20/20

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68      103x   103x                       103x                               910x 910x       1820x 1820x 1820x 532x 532x 532x       83930x 83930x       1820x 1820x 8666x   78162x           532x 532x 1596x      
import type { UnitTypeEnum } from "@/api/apiStore.gen";
import { GetUnitSet } from "@/data/UnitsLibrary";
 
const ANNUAL_ENERGY_UNITS = ["MWh/year", "kWh/year", "GJ/year"] as const;
 
const UNIT_TYPE = {
  Area: "area" as UnitTypeEnum,
  Energy: "energy" as UnitTypeEnum,
  Heatflow: "heatflow" as UnitTypeEnum,
  Mass: "mass" as UnitTypeEnum,
  Massflow: "massflow" as UnitTypeEnum,
  Ratio: "ratio" as UnitTypeEnum,
  Time: "time" as UnitTypeEnum,
  Volume: "volume" as UnitTypeEnum,
  VolumetricFlow: "volumetricFlow" as UnitTypeEnum,
} as const;
 
const UNIT_FAMILY_TYPES = [
  UNIT_TYPE.Massflow,
  UNIT_TYPE.VolumetricFlow,
  UNIT_TYPE.Heatflow,
  UNIT_TYPE.Energy,
  UNIT_TYPE.Mass,
  UNIT_TYPE.Time,
  UNIT_TYPE.Volume,
  UNIT_TYPE.Area,
  UNIT_TYPE.Ratio,
] as const;
 
export function costCurveUnitsCompatible(
  driverUnit: string,
  curveUnit: string,
) {
  Iif (driverUnit === curveUnit) return true;
  return unitFamily(driverUnit) === unitFamily(curveUnit);
}
 
function unitFamily(unit: string) {
  const normalized = normalizeEconomicsUnitNotation(unit);
  const unitType = unitTypeForUnit(normalized);
  if (unitType) return unitType;
  Iif (isAnnualEnergyUnit(normalized)) return "annual-energy";
  Iif (["w", "kw", "mw", "gw"].includes(normalized)) return "power";
  return normalized;
}
 
function normalizeEconomicsUnitNotation(unit: string) {
  const normalized = unit.trim().toLowerCase().replace(/ /g, "");
  return normalized.replace(/^m3(?=\/|$)/, "m^3");
}
 
function unitTypeForUnit(unit: string) {
  const normalizedUnit = normalizeEconomicsUnitNotation(unit);
  return UNIT_FAMILY_TYPES.find((unitType) =>
    GetUnitSet(unitType).some(
      (candidate) =>
        normalizeEconomicsUnitNotation(candidate.value) === normalizedUnit,
    ),
  );
}
 
function isAnnualEnergyUnit(unit: string) {
  const normalizedUnit = normalizeEconomicsUnitNotation(unit);
  return ANNUAL_ENERGY_UNITS.some(
    (candidate) => normalizeEconomicsUnitNotation(candidate) === normalizedUnit,
  );
}