@neutrium/quantity - v5.0.0
    Preparing search index...

    Class Quantity

    Quantity configured with NearleyQtyParser. Import from @neutrium/quantity. Values and counted units are read-only; arithmetic, conversions, and clones retain the receiving class and parser.

    Use withConfig to isolate Decimal settings and configure cache budgets.

    import { Quantity } from '@neutrium/quantity';

    const PreciseQuantity = Quantity.withConfig({ precision: 30 });
    new PreciseQuantity('2 m').to('cm').scalar.toString(); // "200"

    Hierarchy

    Index
    • Construct a quantity from an expression, scalar, definition, or existing quantity.

      Parameters

      • input: QuantityInitParam

        Quantity expression, number, Decimal, numeric toString() object, or definition containing a Decimal scalar and counted unit records.

      • Optionalunits: string

        Optional unit expression. Omitted or empty units make scalar inputs dimensionless. A scalar in this expression is replaced by input. Ignored for definitions and existing quantities.

      • Optionalparser: Parser<QuantityDefinition>

        Per-instance override; otherwise uses this class's default parser with its configured cache limits. Derived results retain the parser.

      Returns Quantity

      If input is invalid, unit counts overflow, or temperature restrictions are violated. External definition scalars must be Decimal instances.

    • Create a new quantity with the same value and units.

      Returns QuantityCore

      A distinct Quantity instance with its own conversion cache.

      The scalar and frozen unit arrays are reused, preserving the configured parser. Treat the original and copy as immutable.

      const original = new Quantity('2 m');
      const copy = original.clone();
      copy === original; // false
      copy.same(original); // true
    • Create a class with isolated numerical settings and optional cache limits.

      Type Parameters

      Parameters

      • this: T
      • config: QuantityConfigInput

        Decimal overrides, parser settings and conversionCache limits, merged with this class's settings.

      Returns T

      A new class whose instances and derived results retain these settings.

      Subclasses with a different constructor signature must override the protected constructQuantity hook. Configuration preserves a constructor's signature; it does not supply additional subclass arguments to derived results.

    • get baseScalar(): ScientificDecimal

      Lazily calculated numerical value in base units; absolute temperatures use kelvin. Recomputed on access when the shared Decimal configuration changes.

      Returns ScientificDecimal

      toBase for a quantity with base units and this value.

    • get denominator(): readonly UnitPower[]

      Counted denominator units; an empty array represents unity. Records and arrays are frozen.

      Returns readonly UnitPower[]

      units for a human-readable expression.

    • get initValue(): QuantityInitParam

      The original scalar/string input, or a normalized value-and-units snapshot for Quantity and definition inputs. Numeric toString() objects are saved as their parsed Decimal scalar. Copies do not retain the source object.

      Returns QuantityInitParam

    • get numerator(): readonly UnitPower[]

      Counted numerator units, such as [{ unit: "<meter>", exponent: 2 }]. Records and arrays are frozen; exponents never expand into repeated entries.

      Returns readonly UnitPower[]

      units for a human-readable expression.

    • get scalar(): ScientificDecimal

      Numerical value in this quantity's units, stored as @neutrium/decimal Decimal.

      Use scalar.toString() to retain decimal digits, or scalar.toNumber() when a JavaScript number is needed and floating-point rounding is acceptable. Read-only; create a new quantity to change the value.

      Returns ScientificDecimal

    • get signature(): string

      Cached dimensional signature. Prefer isCompatible over interpreting this string.

      Returns string

    • Format the counted units as a unit expression.

      Returns string

      The expression without its scalar; an empty string for a unitless quantity.

      Spelling and grouping may differ from the input. Powers use compact notation such as m2; numerator multiplication uses * and denominator multiplication uses tightly coupled ., as in kg/m.s. Output aliases preserve unit identity when parsed by either bundled parser. The result is cached.

      new Quantity('3 meter').units(); // "m"
      new Quantity('3 m^2').units(); // "m2"
      new Quantity('3 kg/m/s').units(); // "kg/m.s"
      new Quantity('3').units(); // ""
    • Test whether every unprefixed unit belongs to the library's base unit set.

      Returns boolean

      True for base units or a unitless quantity; false for scaled or derived units.

      new Quantity('1 m').isBase(); // true
      new Quantity('1 cm').isBase(); // false
    • Convert to compatible units, or reciprocal units by inverting the quantity.

      Parameters

      • other: string | QuantityCore

        Target unit expression or Quantity. Only the units are used; any target scalar is ignored, including zero or negative values.

      Returns QuantityCore

      The quantity expressed in the target units. Empty target strings and unchanged units return this instance; repeated conversions can return cached objects.

      If parsing fails, dimensions are neither compatible nor reciprocal, or reciprocal conversion requires inverting a zero value or absolute temperature.

      const mass = new Quantity('25 kg');
      mass.to('g').scalar.toString(); // "25000"
      mass.to(new Quantity('3 g')).scalar.toString(); // "25000"
      new Quantity('2 m').to('m^-1').scalar.toString(); // "0.5"

      toBase

    • Convert this quantity to the library's base unit system.

      Returns QuantityCore

      A quantity in base units, or this instance if it already uses base units. Absolute temperatures are converted to tempK with the appropriate offset.

      new Quantity('250 cm').toBase().scalar.toString(); // "2.5"
      new Quantity('250 cm').toBase().units(); // "m"
      new Quantity('0 tempC').toBase().scalar.toString(); // "273.15"
    • Add a quantity after converting it to compatible units.

      Parameters

      • other: QuantityInitParam

        A quantity expression, definition, Quantity, or scalar input. Scalars without units are dimensionless and require a compatible receiver.

      Returns QuantityCore

      A new quantity, normally in this quantity's units. Adding degrees to an absolute temperature returns an absolute temperature.

      If units are incompatible, the input is invalid, two absolute temperatures are added, or the result is below absolute zero.

      new Quantity('1 m').add('25 cm').scalar.toString(); // "1.25"
      
    • Divide by a scalar or combine units with another quantity.

      Parameters

      • other: QuantityInitParam

        A number, Decimal, numeric toString() object, quantity expression, definition, or Quantity.

      Returns QuantityCore

      A new quotient. Divisors without unit tokens preserve the current units, including numeric strings and dimensionless Quantity instances. Compatible quantities are converted before division, except for temperature degrees.

      If parsing fails, the divisor is an absolute temperature, or an absolute temperature is divided by a value with units.

      Validate zero divisors when accepting user input; this method delegates scalar division to Decimal rather than explicitly rejecting zero.

      new Quantity('100 km').div('2 h').scalar.toString(); // "50"
      new Quantity('1 m').div('25 cm').isUnitless(); // true
    • Take the reciprocal of the scalar and swap numerator and denominator units.

      Returns QuantityCore

      A new reciprocal quantity.

      If the scalar is zero or this is an absolute temperature.

      new Quantity('2 m').inverse().scalar.toString(); // "0.5"
      new Quantity('2 m').inverse().units(); // "1/m"
    • Multiply by a scalar or combine units with another quantity.

      Parameters

      • other: QuantityInitParam

        A number, Decimal, numeric toString() object, quantity expression, definition, or Quantity.

      Returns QuantityCore

      A new product. Scalars and quantities without unit tokens preserve the other operand's units. Compatible quantities are converted to the left operand's units before multiplication, except for temperature degrees.

      If parsing fails, absolute temperatures are multiplied by a value with units, or the result is an invalid absolute temperature.

      new Quantity('3 m').mul(2).scalar.toString(); // "6"
      new Quantity('3 m').mul('2 m').units(); // "m2"
    • Raise the scalar and units to an integer power.

      Parameters

      • yy: string | number | ScientificDecimal

        Integer exponent as a number, decimal string, or Decimal. Negative exponents invert the unit expression.

      Returns QuantityCore

      A new quantity with the powered scalar and units.

      If the exponent is fractional or invalid, or the resulting units violate absolute-temperature restrictions. Exponents and resulting counts outside the safe-integer range throw RangeError.

      Exponent zero returns the dimensionless identity, with scalar one. Units are stored as counters; powers never allocate repeated unit entries. Exponent validation is independent of the quantity's Decimal range settings; those settings apply to the resulting scalar.

      new Quantity('3 m').pow(2).scalar.toString(); // "9"
      new Quantity('3 m').pow(2).units(); // "m2"
    • Subtract a quantity after converting it to compatible units.

      Parameters

      • other: QuantityInitParam

        A quantity expression, definition, Quantity, or scalar input. Scalars without units are dimensionless and require a compatible receiver.

      Returns QuantityCore

      A new quantity in this quantity's units, except that subtracting two absolute temperatures returns temperature degrees.

      If units are incompatible, the input is invalid, an absolute temperature is subtracted from degrees, or the result is below absolute zero.

      new Quantity('1 m').sub('25 cm').scalar.toString(); // "0.75"
      new Quantity('30 tempC').sub('20 tempC').units(); // "degC"
    • Compare compatible physical values, or a numeric value in the current units.

      Parameters

      • b: string | number | ScientificDecimal | QuantityCore

        Quantity or quantity expression, or a number/Decimal in this quantity's current units. Numeric operands require no parsing or temporary Quantity.

      Returns 0 | 1 | -1 | undefined

      -1 if this quantity is smaller, 0 if equal, or 1 if larger; undefined when either value is NaN. Boolean comparisons return false for NaN.

      If the expression is invalid or the units are incompatible. Reciprocal units are not comparable; convert them explicitly first if appropriate.

      new Quantity('1 m').compareTo('50 cm'); // 1
      new Quantity('1 m').compareTo('100 cm'); // 0
      new Quantity('10 m').compareTo(5); // 1 (10 m compared with 5 m)
    • Test whether this physical value is equal to another compatible value.

      Parameters

      • b: string | number | ScientificDecimal | QuantityCore

        Quantity or expression, or a number/Decimal in this quantity's current units.

      Returns boolean

      Whether the comparison holds. Numeric operands compare directly with the scalar; Quantity and string operands compare compatible physical values. NaN returns false.

      If the expression is invalid or units are incompatible.

      new Quantity('1 m').eq('100 cm'); // true
      

      compareTo for three-way comparison.

    • Test whether this physical value is greater than another compatible value.

      Parameters

      • b: string | number | ScientificDecimal | QuantityCore

        Quantity or expression, or a number/Decimal in this quantity's current units.

      Returns boolean

      Whether the comparison holds. Numeric operands compare directly with the scalar; Quantity and string operands compare compatible physical values. NaN returns false.

      If the expression is invalid or units are incompatible.

      new Quantity('1 m').gt('50 cm'); // true
      

      compareTo for three-way comparison.

    • Test whether this physical value is greater than or equal to another compatible value.

      Parameters

      • b: string | number | ScientificDecimal | QuantityCore

        Quantity or expression, or a number/Decimal in this quantity's current units.

      Returns boolean

      Whether the comparison holds. Numeric operands compare directly with the scalar; Quantity and string operands compare compatible physical values. NaN returns false.

      If the expression is invalid or units are incompatible.

      new Quantity('1 m').gte('100 cm'); // true
      

      compareTo for three-way comparison.

    • Test whether two quantities have the same dimensional signature.

      Parameters

      • b: string | number | QuantityCore

        A Quantity or unit expression; numeric inputs return false.

      Returns boolean

      Whether dimensions match, without comparing scalars or converting units. Absolute temperatures and temperature degrees share a signature.

      If a string cannot be parsed.

      const length = new Quantity('1 m');
      length.isCompatible('cm'); // true
      length.isCompatible('s'); // false
    • Test whether another quantity has reciprocal dimensions.

      Parameters

      • b: string | QuantityCore

        A Quantity or expression describing the reciprocal units.

      Returns boolean

      Whether all dimensional exponents are the negatives of those in b. Scalars are ignored, including zero. Absolute temperatures and temperature degrees share a dimension; this check does not imply that inversion is allowed.

      If a string cannot be parsed.

      Existing Quantity operands require no parsing or temporary quantities. Actual reciprocal conversion still rejects zero values and absolute temperatures.

      new Quantity('2 m').isInverse('m^-1'); // true
      new Quantity('0 m').isInverse('m^-1'); // true
    • Test whether the normalized numerator and denominator are both unity.

      Returns boolean

      True for a quantity without unit tokens. Named dimensionless units such as radians and each return false.

      new Quantity('2').isUnitless(); // true
      new Quantity('2 rad').isUnitless(); // false
    • Test whether this physical value is less than another compatible value.

      Parameters

      • b: string | number | ScientificDecimal | QuantityCore

        Quantity or expression, or a number/Decimal in this quantity's current units.

      Returns boolean

      Whether the comparison holds. Numeric operands compare directly with the scalar; Quantity and string operands compare compatible physical values. NaN returns false.

      If the expression is invalid or units are incompatible.

      new Quantity('1 m').lt('2 m'); // true
      

      compareTo for three-way comparison.

    • Test whether this physical value is less than or equal to another compatible value.

      Parameters

      • b: string | number | ScientificDecimal | QuantityCore

        Quantity or expression, or a number/Decimal in this quantity's current units.

      Returns boolean

      Whether the comparison holds. Numeric operands compare directly with the scalar; Quantity and string operands compare compatible physical values. NaN returns false.

      If the expression is invalid or units are incompatible.

      new Quantity('1 m').lte('100 cm'); // true
      

      compareTo for three-way comparison.

    • Test exact scalar equality and matching normalized unit records.

      Parameters

      Returns boolean

      Whether scalars and ordered unit/prefix/exponent records match. Different compatible units return false even when they represent the same physical value.

      const length = new Quantity('1 m');
      length.same(new Quantity('100 cm')); // false
      length.eq('100 cm'); // true
    • Test for a standalone, unprefixed temperature unit, including absolute temperatures.

      Returns boolean

      True for both degC-style intervals and tempC-style absolute temperatures. To identify an unprefixed interval, combine this with !qty.isTemperature(). Prefixed and compound interval units return false; use isCompatible('degK') for a dimensional check.

      new Quantity('20 degC').isDegrees(); // true
      new Quantity('20 tempC').isDegrees(); // true
      new Quantity('20 degC/m').isDegrees(); // false
    • Test whether this quantity represents an absolute temperature.

      Returns boolean

      True for standalone tempC, tempF, tempK, or tempR units.

      new Quantity('20 tempC').isTemperature(); // true
      new Quantity('20 degC').isTemperature(); // false