@neutrium/quantity - v7.1.0
    Preparing search index...

    Class Quantity<T, Numeric>Abstract

    A numeric scalar paired with units, with conversion, arithmetic, and comparison operations.

    Import from @neutrium/quantity. Construct quantities with new and read the numerical result through scalar; units returns the unit expression.

    Existing Quantity operands used for arithmetic or value comparisons must have compatible numeric backends. Use new DestinationQuantity(source) to convert explicitly. Dimensional predicates and conversion targets use units only. Arithmetic produces quantities without changing the operands. Conversions may return the same instance or a cached result. Treat quantities and their unit arrays as immutable. Public values are getter-only; create a new quantity to change them. Counted unit records and arrays are frozen and may be shared.

    Methods are shared on the prototype and require a Quantity receiver. When passing a method as a callback, use an arrow wrapper or bind it to the instance.

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

    const speed = new Quantity('100 km').div('2 h').to('km/h');
    speed.scalar.toString(); // "50"
    speed.units(); // "km/h"

    Type Parameters

    • T = Decimal
    • Numeric extends object = object
    Index
    • Create a quantity from an expression, a scalar and units, or a parsed definition.

      Type Parameters

      • T = ScientificDecimal
      • Numeric extends object = object

      Parameters

      • initValue: QuantityInput<T>

        A full expression such as "3 m", a scalar paired with initUnits, or a QuantityDefinition / existing Quantity.

      • initUnits: string | undefined

        Nonempty unit expression for a separate scalar. A scalar in this expression is replaced by initValue. Ignored for quantity and definition inputs.

      • parser: Parser<T>

        Parser used for string expressions; supplied by the configured entry point. Required even for definitions; retained for subsequent string operations.

      Returns Quantity<T, Numeric>

      If inputs cannot be parsed, an absolute temperature is below absolute zero, or absolute-temperature units occur in a compound expression.

      Numbers, bigints, native backend scalars, numeric strings and objects with numeric toString() output create dimensionless quantities when units are omitted or empty. Use a decimal string or Decimal when preserving all input digits matters. An existing quantity keeps its units and converts its scalar to this backend. Absolute readings account for any difference between the represented absolute-zero boundaries. Native destinations use numeric conversion; rational-capable backends can exchange exact terms. Other custom representations fall back to numeric text. Destination range and representation limits apply, and precision already lost cannot be recovered.

      const length = new Quantity('1.25', 'm');
      const unit = new Quantity('m'); // scalar defaults to 1
      const ratio = new Quantity(2); // dimensionless
      const copy = new Quantity(length);
    • Create a new quantity with the same value and units.

      Returns Quantity<T, Numeric>

      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

      • C extends new (...args: never[]) => Quantity<any>

      Parameters

      • this: C
      • config: QuantityConfigInput<object>

        Nested numeric options and cache policies, merged with this class's settings.

      Returns C

      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. Numeric settings require a configurable adapter. Omitted settings inherit from this class; cache: false disables optional Quantity caches and true resets them.

      const Uncached = Quantity.withConfig({ cache: false });
      const q = new Uncached('2 m');
      q.config === Uncached.config; // true
    • get baseScalar(): T

      Lazily calculated numerical value in base units; absolute temperatures use kelvin. Reused after first access when cache.metadata is enabled; otherwise recalculated.

      Returns T

      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(): QuantityInput<T>

      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 backend scalar. Copies do not retain the source object. Snapshots are created on first access, frozen, and reused on subsequent reads.

      Returns QuantityInput<T>

    • 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(): T

      Numerical value in this quantity’s units, represented by the selected backend.

      Use qty.numeric.toString(qty.scalar) for numeric text across backends, or qty.numeric.toNumber(qty.scalar) for a JavaScript number (which may lose precision). Read-only; create a new quantity to change the value.

      Returns T

    • 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 any of the three bundled parsers. The result is cached when cache.metadata is enabled; custom parsers may use a different input syntax.

      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 | Quantity<unknown, object>

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

      Returns Quantity<T, Numeric>

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

      TypeError if the target is neither a string nor a Quantity.

      If parsing fails, dimensions are neither compatible nor reciprocal, or reciprocal conversion requires inverting a zero value or absolute temperature. Invalid absolute-temperature results throw; valid results requiring a negative-infinite reading or unrepresentable absolute-zero boundary throw RangeError.

      An existing target supplies units only, including when its backend differs. The result keeps this quantity's backend, configuration and parser.

      import { Quantity as NumberQuantity } from '@neutrium/quantity/number';
      const mass = new Quantity('25 kg');
      mass.to('g').scalar.toString(); // "25000"
      mass.to(new Quantity('3 g')).scalar.toString(); // "25000"
      mass.to(new NumberQuantity('0 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 Quantity<T, Numeric>

      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 compatible quantity, accounting for its unit scale.

      Parameters

      • other: QuantityOperand<T>

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

      Returns Quantity<T, Numeric>

      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. Incompatible backends throw TypeError; a valid but unrepresentable negative absolute reading throws RangeError.

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

      Parameters

      • other: QuantityOperand<T>

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

      Returns Quantity<T, Numeric>

      A new quotient. Divisors without unit tokens preserve the current units, including numeric strings and dimensionless Quantity instances. Compatible quantities align to the left operand's units, except for temperature degrees. Decimal rounds the complete quotient once; other backends follow their own arithmetic.

      If parsing fails, the divisor is an absolute temperature, or an absolute temperature is divided by a value with units. Incompatible backends throw TypeError. Invalid absolute readings throw; valid but unrepresentable negative readings throw RangeError.

      Validate zero divisors when accepting user input; this method delegates scalar division to the numeric adapter 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 Quantity<T, Numeric>

      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: QuantityOperand<T>

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

      Returns Quantity<T, Numeric>

      A new product. Scalars and quantities without unit tokens preserve the other operand's units. Compatible quantities align to the left operand's units, except for temperature degrees. Decimal rounds the complete product once; other backends follow their own arithmetic and intermediate rounding.

      If parsing fails, absolute temperatures are multiplied by a value with units, or the result is an invalid absolute temperature. Incompatible backends throw TypeError; an unrepresentable valid negative absolute reading throws RangeError.

      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 exact rational power.

      Parameters

      • yy: string | number | RationalFraction | T

        Exponent as a number, decimal or fraction string, backend scalar, or rational record. Negative exponents invert the unit expression.

      Returns Quantity<T, Numeric>

      A new quantity with the powered scalar and units.

      If the exponent is invalid, the adapter cannot evaluate a fractional power, an even root has a negative scalar, or the resulting units violate absolute-temperature restrictions. Exponents and resulting counts outside the safe-integer magnitude range throw RangeError. Decimal exponent expansion is limited to 4096 places.

      Exponent zero returns the dimensionless identity, with scalar one. Fractional powers require rational extraction and construction or a scientific adapter. Both Decimal adapter tiers support them. If a custom adapter lacks rational extraction and rounds its exponent text, pass an explicit exponent string or rational record. Units are stored as counters; powers never allocate repeated unit entries. Exponent validation is independent of the numeric backend's 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 compatible quantity, accounting for its unit scale.

      Parameters

      • other: QuantityOperand<T>

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

      Returns Quantity<T, Numeric>

      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. Incompatible backends throw TypeError; an unrepresentable valid negative absolute reading throws RangeError.

      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 | T | Quantity<T, object>

        Quantity or quantity expression, or a number/backend scalar 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, units are incompatible, or quantity backends 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 | T | Quantity<T, object>

        Quantity or expression, or a number/backend scalar 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, units are incompatible, or quantity backends 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 | T | Quantity<T, object>

        Quantity or expression, or a number/backend scalar 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, units are incompatible, or quantity backends 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 | T | Quantity<T, object>

        Quantity or expression, or a number/backend scalar 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, units are incompatible, or quantity backends 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 | Quantity<unknown, object>

        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. This check does not establish backend compatibility or permission for temperature arithmetic.

      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 | Quantity<unknown, object>

        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. A named unit such as a radian returns 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 | T | Quantity<T, object>

        Quantity or expression, or a number/backend scalar 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, units are incompatible, or quantity backends 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 | T | Quantity<T, object>

        Quantity or expression, or a number/backend scalar 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, units are incompatible, or quantity backends 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

      • b: Quantity<T>

        Quantity to compare with this instance.

      Returns boolean

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

      TypeError when the argument is not a Quantity or the numeric backends are incompatible.

      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