BBizKit

qty.sub

v0.1.0 latest

Subtract two Quantity values with same-unit enforcement (case-sensitive comparison).

quantityarithmeticsubtractionucummeasurement

Subtract two Quantity values with same-unit enforcement (case-sensitive comparison).

Signature

function sub(a: Quantity, b: Quantity): Quantity

Type Definitions:

Problem

Subtracting physical quantities requires the same unit validation as addition. Result can be negative (e.g. temperature drop, weight loss).

How It Works

Validates same unit (case-sensitive), then subtracts values. Result can be negative.

Boundaries

  • Unit mismatch → TypeError.
  • Result can be negative.

Replaces

Common boilerplate this function replaces:

if (a.unit !== b.unit) throw new Error('unit mismatch'); return { value: a.value - b.value, unit: a.unit };

Examples

qty.sub({ value: 10, unit: "kg" }, { value: 3, unit: "kg" });  // { value: 7, unit: "kg" }
qty.sub(qty.parse("5 m")!, qty.parse("3 m")!);  // { value: 2, unit: "m" }

Standards

Caveats

  • Same unit enforcement and precision caveats as qty.add.
  • Result can be negative — represents decreases or deficits.

FAQ

How to subtract physical quantities in JavaScript?

qty.sub(a, b) subtracts two Quantity values after verifying same unit.

Can qty.sub return negative values?

Yes. qty.sub({ value: 3, unit: 'kg' }, { value: 5, unit: 'kg' }) returns { value: -2, unit: 'kg' }.

What validation does qty.sub perform?

Same as qty.add: unit mismatch throws TypeError.

Is qty.sub exact?

IEEE 754 double precision — same as normal JavaScript number arithmetic.

Does qty.sub convert units?

No. Both operands must share the same unit.