qty.add
v0.1.0 latestAdd two Quantity values with same-unit enforcement (case-sensitive comparison).
Add two Quantity values with same-unit enforcement (case-sensitive comparison).
Signature
function add(a: Quantity, b: Quantity): Quantity
Type Definitions:
Quantity— interface
Problem
Adding physical quantities requires unit validation. Silently adding kg + lb produces meaningless results. No implicit unit conversion avoids hidden policy decisions.
How It Works
Validates that both operands have the same unit (case-sensitive), then adds their values.
Boundaries
- Unit mismatch → TypeError (e.g. 'kg' + 'lb' is rejected).
- No unit conversion is performed — this is intentional to avoid implicit policy.
- Uses IEEE 754 number addition (subject to floating-point precision limits).
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.add({ value: 10, unit: "kg" }, { value: 5.5, unit: "kg" }); // { value: 15.5, unit: "kg" }
qty.add(qty.parse("10 kg")!, qty.parse("5.5 kg")!); // { value: 15.5, unit: "kg" }
Standards
Caveats
- Unit comparison is case-sensitive: 'kg' and 'Kg' are different units.
- No unit conversion — callers must convert to the same unit before adding.
FAQ
How to add physical quantities in JavaScript?
qty.add(a, b) adds two Quantity values after verifying they share the same unit.
Does qty.add convert units?
No. Adding kg + lb throws TypeError. Convert to the same unit first.
Is unit comparison case-sensitive?
Yes. 'kg' and 'Kg' are different units and cannot be added.
Why doesn't qty.add convert units automatically?
Implicit unit conversion is a policy decision. The library avoids hidden policies per its design philosophy.
What precision does qty.add use?
IEEE 754 double. Subject to floating-point precision limits.