ChemPal Documentation - v1.6.0
    Preparing search index...

    Function toCostBaseQuantity

    • Normalizes a quantity to the base unit used for per-unit cost comparison: grams for mass, millilitres for volume, and the unchanged countable unit for pieces/each. Unlike toBaseQuantity (which returns milligrams for mass), this steps mass up to grams so a cost-per-gram reads naturally. Returns undefined for an unrecognized unit or a non-positive quantity, so callers can safely divide by the result.

      Parameters

      • quantity: number

        The quantity to convert.

      • uom: string

        The unit of measure of the quantity (canonical or alias form).

      Returns undefined | QuantityObject

      The quantity in its cost base unit (g / ml / countable), or undefined.

      toCostBaseQuantity(1, "kg")  // Returns { quantity: 1000, uom: "g" }
      toCostBaseQuantity(2, "l") // Returns { quantity: 2000, uom: "ml" }
      toCostBaseQuantity(5, "pcs") // Returns { quantity: 5, uom: "pcs" }
      toCostBaseQuantity(0, "g") // Returns undefined
      export function toCostBaseQuantity(quantity: number, uom: string): QuantityObject | undefined {
      if (typeof quantity !== 'number' || quantity <= 0) return undefined;

      const standardized = standardizeUom(uom);
      if (!standardized) return undefined;

      switch (getUomKind(standardized)) {
      case 'mass':
      // toBaseQuantity returns milligrams for mass; step up to grams.
      return { quantity: toBaseQuantity(quantity, standardized) / 1000, uom: UOM.G };
      case 'volume':
      return { quantity: toBaseQuantity(quantity, standardized), uom: UOM.ML };
      case 'count':
      return { quantity, uom: standardized };
      default:
      return undefined;
      }
      }