All files / src/helpers quantity.ts

98.39% Statements 184/187
88.75% Branches 71/80
100% Functions 10/10
98.39% Lines 184/187

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 4161x 1x 1x   1x   1x           1x   1x       1x 1x 1x 1x 1x 1x                           1x     1x 1x 1x 1x 1x 1x 1x 1x   1x                             1x 1x 642x   642x   93x 93x 93x 93x 93x   1x                                         1x 1x 690x   679x 679x   690x   626x   626x 626x 686x 94x 94x 94x   626x 626x 690x   690x 690x   1x                                     1x 1x 22x   22x   22x 22x   1x                                 1x 1x 806x 806x 9672x 37882x 37882x 9672x   806x 806x 806x 806x   1x                               1x 1x 91x   91x 91x 91x 1x 91x 43x 91x 6x 91x 11x 91x 91x   91x 91x 5x 91x 9x 91x 3x 91x 10x 91x 1x   91x 91x 91x     91x 1x 1x 91x 91x   1x                   1x 16x 16x 16x   1x                                   1x 1x 40x 40x   40x 12x 12x 12x 12x   40x 4x 4x 4x 4x   24x 24x                   1x                               1x 1x 50x 50x   50x 50x 50x 50x 50x 50x 32x 50x 50x 50x 50x 50x 9x 50x 50x 5x 50x 4x 50x 50x   1x                                       1x 1x 39x   36x 39x   36x 39x 26x 26x 39x 4x 39x 3x 39x 3x 39x 39x   1x                                         1x 1x 27x 16x 27x 1x 27x   27x   27x 15x 27x 27x  
import { UOM, UOM_ALIASES, type Uom } from '@/constants/common';
import { isUOM } from '@/utils/typeGuards/common';
import { Logger } from '@/utils/Logger';
 
const logger = new Logger('quantity');
 
/**
 * Quantity parsing and unit conversion utilities for handling different units of measurement.
 * @categoryDescription Helpers
 * @group Quantity
 * @showGroups
 * @showCategories
 */
 
/**
 * Pattern for matching quantities in strings.
 * @see https://regex101.com/r/If0dLa/1
 * @source
 */
const quantityPattern =
  String.raw`(?:(?<multiplier>[1-9][0-9]*)\s*[xX\u00D7]\s*(?=[1-9]))?` +
  String.raw`(?<quantity>[1-9][0-9]*(?:[.,]\d+)*(?:\s\d{3})*)\s?` +
  String.raw`(?<uom>(?:milli|kilo|centi)?(?:ml|ounce|g(?:al(?:lon)?|ram)|ea(?:ch)?|pound|q(?:uar)?t|p(?:iece|c)s?|lb|(?:met|lit)[re]{2})s?|(?:fl\.?\s?)?oz|k[mg]?|gm?|l|[cm]?[gl])s?` +
  String.raw`(?!\/mol)(?![A-Za-z])`;
 
/**
 * @type QuantityObject
 * @group Quantity
 */
type QuantityObject = { quantity: number; uom: string };
 
/**
 * @type UnitConversion
 * @group Quantity
 */
type UnitConversion = { threshold: number; factor: number; from: string; to: string };
 
/**
 * @type unitConversions
 * @group Quantity
 */
const unitConversions: UnitConversion[] = [
  { threshold: 1000, factor: 1000, from: 'g', to: 'kg' },
  { threshold: 1000, factor: 1000, from: 'mg', to: 'g' },
  { threshold: 1000, factor: 1000, from: 'kg', to: 't' },
  { threshold: 1000, factor: 1000, from: 'ml', to: 'l' },
  { threshold: 100, factor: 100, from: 'cm', to: 'm' },
];
 
/**
 * Normalizes a quantity object to its base unit of measure.
 * @category Helpers
 * @group Quantity
 * @param input - The quantity object to normalize
 * @returns The normalized quantity object
 * @example
 * ```typescript
 * normalizeQuantity({ quantity: 1000, uom: "g" }) // Returns { quantity: 1, uom: "kg" }
 * normalizeQuantity({ quantity: 1000, uom: "mg" }) // Returns { quantity: 1, uom: "g" }
 * normalizeQuantity({ quantity: 1000, uom: "kg" }) // Returns { quantity: 1, uom: "t" }
 * normalizeQuantity({ quantity: 1000, uom: "ml" }) // Returns { quantity: 1, uom: "l" }
 * normalizeQuantity({ quantity: 1000, uom: "cm" }) // Returns { quantity: 1, uom: "m" }
 * ```
 * @source
 */
export function normalizeQuantity(input: QuantityObject): QuantityObject {
  const conversion = unitConversions.find((c) => c.from === input.uom.toLowerCase());
 
  if (!conversion || input.quantity < conversion.threshold) return input;
 
  return {
    quantity: Math.round((input.quantity / conversion.factor) * 100) / 100,
    uom: conversion.to,
  };
}
 
/**
 * Parses a quantity string into a structured object containing the numeric value and unit of measure.
 * Handles various formats including foreign number formats (e.g., 1.234,56).
 * Uses regex pattern matching to extract quantity and unit information.
 * @category Helpers
 * @group Quantity
 * @param  value - The quantity string to parse (e.g., '100g', '120 grams')
 * @returns Object containing quantity and UOM, or undefined if parsing fails
 * @throws  If the quantity string cannot be parsed
 *
 * @example
 * ```typescript
 * parseQuantity('100g') // Returns { quantity: 100, uom: 'g' }
 * parseQuantity('120 grams') // Returns { quantity: 120, uom: 'grams' }
 * parseQuantity('43.4 ounce') // Returns { quantity: 43.4, uom: 'ounce' }
 * parseQuantity('1200 milliliters') // Returns { quantity: 1200, uom: 'milliliters' }
 * parseQuantity('1.2 L') // Returns { quantity: 1.2, uom: 'L' }
 * parseQuantity('1.2 g/mol') // Returns nothing, as g/mol is not a quantity
 * ```
 * @see https://regex101.com/r/Ruid54/9
 * @source
 */
export function parseQuantity(value: string): QuantityObject | void {
  if (!value) return;
 
  const quantityPatternRegex = new RegExp(quantityPattern, 'i');
  const quantityMatch = value.match(quantityPatternRegex);
 
  if (!quantityMatch?.groups?.quantity || !quantityMatch?.groups?.uom) return;
 
  let parsedQuantity: string | number = quantityMatch.groups.quantity;
 
  // Handle foreign number formats where commas and decimals are swapped
  if (parsedQuantity.match(/^(\d+\.\d+,\d{1,2}|\d{1,3},\d{1,2}|\d{1,3},\d{1,2})$/))
    parsedQuantity = parsedQuantity
      .replaceAll('.', 'xx')
      .replaceAll(',', '.')
      .replaceAll('xx', ',');
 
  const uom = standardizeUom(quantityMatch.groups.uom);
  const quantity = Number(parsedQuantity.replaceAll(/[,\s]/g, ''));
  const multiplier = Number(quantityMatch.groups?.multiplier ?? '1');
 
  if (uom && quantity) return normalizeQuantity({ quantity: quantity * multiplier, uom });
}
 
/**
 * Strips the quantity from a string. This is useful for when some suppliers don't have products
 * listed as variants, but instead have multiple products with a quantity in the name. Using this
 * function, we can get the name of the product without the quantity, which may be identical to
 * the other variations. Making it easy to group the products into a single listing with multiple
 * variants.
 * @category Helpers
 * @group Quantity
 * @param value - The string to strip the quantity from
 * @returns The string with the quantity removed
 * @example
 * ```typescript
 * stripQuantityFromString("Some reagent - 100g") // Returns "Some reagent -"
 * stripQuantityFromString("120 grams, of some reagent") // Returns "of some reagent"
 * stripQuantityFromString("43.4 ounce of some reagent") // Returns "ounce of some reagent"
 * stripQuantityFromString("1200 milliliters of some reagent") // Returns "milliliters of some reagent"
 * stripQuantityFromString("1.2 L of some reagent") // Returns "L of some reagent"
 * ```
 * @source
 */
export function stripQuantityFromString(value: string): string {
  if (!value || typeof value !== 'string') return value;
 
  const quantityPatternRegex = new RegExp(quantityPattern, 'ig');
 
  return value.replace(quantityPatternRegex, '').trim();
}
 
/**
 * Standardizes a unit of measure (UOM) to its canonical form.
 * Uses the uomAliases mapping to convert various representations to standard forms.
 * @category Helpers
 * @group Quantity
 * @param uom - The unit of measure to standardize
 * @returns The standardized UOM, or undefined if not recognized
 *
 * @example
 * ```typescript
 * standardizeUom('qt') // Returns 'quart'
 * standardizeUom('kg') // Returns 'kilogram'
 * standardizeUom('kilograms') // Returns 'kilogram'
 * standardizeUom('lb') // Returns 'pound'
 * standardizeUom('Grams') // Returns 'gram'
 * ```
 * @source
 */
export function standardizeUom(uom: string): Uom | void {
  const uomMap: Record<string, string> = { [uom]: uom };
  for (const [canonical, aliases] of Object.entries(UOM_ALIASES)) {
    for (const alias of aliases) {
      uomMap[alias] = canonical;
    }
  }
 
  const normalized = uom.toLowerCase();
  // uomMap values are canonical UOM enum strings, widened to string by Record<string, string>.
  if (normalized in uomMap) return uomMap[normalized] as Uom;
}
 
/**
 * Converts a quantity from its current unit to a common unit of mass or volume.
 * This is to make it easier to compare quantities of different units.
 * @category Helpers
 * @group Quantity
 * @param quantity - The quantity to convert
 * @param unit - The unit of measure of the quantity
 * @returns The converted quantity in its base unit
 *
 * @example
 * ```typescript
 * toBaseQuantity(1, UOM.KG) // Returns 1000 (kilograms)
 * toBaseQuantity(1, UOM.LB) // Returns 453.592 (grams)
 * toBaseQuantity(1, UOM.G) // Returns 1 (no conversion needed)
 * ```
 * @source
 */
export function toBaseQuantity(quantity: number, unit: string): number {
  if (typeof quantity !== 'number') return quantity;
 
  switch (unit) {
    // Solids, convert all to milligrams
    case UOM.MG:
      return quantity;
    case UOM.G:
      return quantity * 1000;
    case UOM.KG:
      return quantity * 1000000;
    case UOM.LB:
      return quantity * 453592;
    case UOM.OZ:
      return quantity * 28349.5; // Weight ounce, not fluid
 
    // Liquids, convert all to milliliters
    case UOM.ML:
      return quantity;
    case UOM.L:
      return quantity * 1000;
    case UOM.QT:
      return quantity * 946.353;
    case UOM.GAL:
      return quantity * 3785.41;
    case UOM.FLOZ:
      return quantity * 29.5735;
 
    // Countable units, no conversion
    case UOM.PCS:
    case UOM.EA:
      return quantity;
 
    default:
      logger.debug(`${quantity} ${unit} -> ${quantity} ${unit} (no conversion found)`);
      return quantity;
  }
}
 
/**
 * Rounds a number to two decimal places, avoiding floating-point noise from the
 * conversion factors (e.g. 0.3 lb becomes 136.0776 g, rounded to 136.08 g).
 * @param value - The number to round
 * @returns The value rounded to two decimal places
 * @example
 * ```typescript
 * roundToHundredths(136.0776) // Returns 136.08
 * ```
 * @source
 */
function roundToHundredths(value: number): number {
  return Math.round(value * 100) / 100;
}
 
/**
 * Converts a quantity to its "standard" (metric) form, leaving metric and
 * countable units untouched. Imperial mass (lb, oz) becomes grams (then
 * normalized up to kg via {@link normalizeQuantity}); imperial volume (gal, qt,
 * fl oz) becomes millilitres (then normalized up to l). Built on
 * {@link toBaseQuantity} for the conversion factors so suppliers can present a
 * single, comparable unit system regardless of how the source lists it.
 * @category Helpers
 * @param input - The quantity object to convert
 * @returns The metric-normalized quantity object (unchanged when already metric or countable)
 * @example
 * ```typescript
 * toMetricQuantity({ quantity: 0.3, uom: "lb" })  // Returns { quantity: 136.08, uom: "g" }
 * toMetricQuantity({ quantity: 2, uom: "lb" })    // Returns { quantity: 907.18, uom: "g" }
 * toMetricQuantity({ quantity: 1, uom: "gal" })   // Returns { quantity: 3.79, uom: "l" }
 * toMetricQuantity({ quantity: 100, uom: "g" })   // Returns { quantity: 100, uom: "g" }
 * ```
 * @source
 */
export function toMetricQuantity(input: QuantityObject): QuantityObject {
  const uom = standardizeUom(input.uom);
  if (!uom) return input;
 
  if (uom === UOM.LB || uom === UOM.OZ) {
    // toBaseQuantity returns milligrams for mass; step up to grams, then normalize (g -> kg).
    const grams = toBaseQuantity(input.quantity, uom) / 1000;
    return normalizeQuantity({ quantity: roundToHundredths(grams), uom: UOM.G });
  }
 
  if (uom === UOM.GAL || uom === UOM.QT || uom === UOM.FLOZ) {
    // toBaseQuantity returns millilitres for volume; normalize (ml -> l).
    const millilitres = toBaseQuantity(input.quantity, uom);
    return normalizeQuantity({ quantity: roundToHundredths(millilitres), uom: UOM.ML });
  }
 
  return input;
}
 
/**
 * The broad category a unit of measure belongs to. Mass and volume units each
 * share a common base scale ({@link toBaseQuantity}); countable units don't
 * convert.
 * @group Quantity
 */
type UomKind = 'mass' | 'volume' | 'count';
 
/**
 * Classifies a unit of measure as mass, volume, or countable. Standardizes the
 * input first (via {@link standardizeUom}), so aliases like `"grams"` or `"lbs"`
 * are accepted. Returns `undefined` for unrecognized units.
 * @category Helpers
 * @group Quantity
 * @param uom - The unit of measure to classify (canonical or alias form).
 * @returns The unit's kind, or `undefined` if the unit isn't recognized.
 * @example
 * ```typescript
 * getUomKind("kg")   // Returns "mass"
 * getUomKind("floz") // Returns "volume"
 * getUomKind("pcs")  // Returns "count"
 * getUomKind("xyz")  // Returns undefined
 * ```
 * @source
 */
export function getUomKind(uom: string): UomKind | undefined {
  const standardized = standardizeUom(uom);
  if (!standardized) return undefined;
 
  switch (standardized) {
    case UOM.MG:
    case UOM.G:
    case UOM.KG:
    case UOM.LB:
    case UOM.OZ:
      return 'mass';
    case UOM.ML:
    case UOM.L:
    case UOM.QT:
    case UOM.GAL:
    case UOM.FLOZ:
      return 'volume';
    case UOM.PCS:
    case UOM.EA:
      return 'count';
    default:
      return undefined;
  }
}
 
/**
 * 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 {@link 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.
 * @category Helpers
 * @group Quantity
 * @param quantity - The quantity to convert.
 * @param uom - The unit of measure of the quantity (canonical or alias form).
 * @returns The quantity in its cost base unit (`g` / `ml` / countable), or `undefined`.
 * @example
 * ```typescript
 * 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
 * ```
 * @source
 */
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;
  }
}
 
/**
 * Formats a unit of measure (UOM) for display.
 * @category Helpers
 * @group Quantity
 * @param uom - The unit of measure to format
 * @returns The formatted UOM
 * @example
 * ```typescript
 * formatUomForDisplay(UOM.ML) // Returns "mL"
 * formatUomForDisplay(UOM.L) // Returns "L"
 * formatUomForDisplay(UOM.KG) // Returns "kg"
 * formatUomForDisplay(UOM.LB) // Returns "lb"
 * formatUomForDisplay(UOM.OZ) // Returns "oz"
 * formatUomForDisplay(UOM.G) // Returns "g"
 * formatUomForDisplay(UOM.QT) // Returns "qt"
 * formatUomForDisplay(UOM.GAL) // Returns "gal"
 * formatUomForDisplay(UOM.FLOZ) // Returns "fl oz"
 * formatUomForDisplay(UOM.PCS) // Returns "pcs"
 * formatUomForDisplay(UOM.EA) // Returns "ea"
 * ```
 * @source
 */
export function formatUomForDisplay(uom: unknown): string {
  if (!isUOM(uom)) return String(uom);
  switch (uom) {
    case UOM.ML:
      return 'mL';
    case UOM.L:
      return 'L';
    case UOM.FLOZ:
      return 'fl oz';
    default:
      return String(uom);
  }
}