Types and utilities for associating units (dimensions) to quantities. The primary use case for Unitopia is applications that deal with like measurements in possibly non-homogenous units. For example, an application that allows the user to switch between pounds and kilograms, or tasks that can be measured in days or weeks.
What it provides:
- Type safety for working with dimensional values, making it more difficult to accidentally compare or perform arithmetic on dissimilar units.
- Ergonomic unit conversion & normalization.
- Serialization and deserialization to JSON.
- Zero dependencies.
Currently available dimensions:
- Length
- Mass (weight)
- Time
Coming soon:
- Money (currency)
- Power (Watt)
- Current (Ampere)
- Voltage (Volt)
Coming not-so-soon:
- Support for derived units & dimensional analysis
To create a quantity object, simply import the appropriate class and use the appropriate static method:
import { Mass } from 'unitopia'
const m1 = Mass.Pounds(100)
const m2 = Mass.Kilograms(22)
The type of m1
will be Mass<'Pound'>
, tye type of m2
will be Mass<'Kilogram'>
. You can also use the Mass
constructor but (currently) it won't be typed to the specific unit:
const m3 = new Mass(2, 'Short Ton')
The type of m3
will be Mass<'Kilogram' | 'Milligram' | 'Gram' | 'Short Ton' |...>
. For this reason, it's preferred to use the convenience constructors illustrated above.
Quantities can be serialized directly with JSON.stringify
:
JSON.stringify(m1) // {"dimension":"Mass","unit":"Pound","value":100}
Deserialize with the parse
or tryParse
methods, which can accept either an object or a string (which will be parsed from JSON):
try {
const m = Mass.parse({ dimension: 'Mass', unit: 'Gram', value: 100 })
console.log(m)
} catch (err) {
console.error('parsing error:', err.message)
}
const res = Mass.tryParse({ dimension: 'Mass', unit: 'Gram', value: 100 })
if ('error' in res) console.error('parsing error:', err.message)
else console.log(res.mass)
Simply call the static convert
method and specify the desired unit:
import { Length } from 'unitopia'
const h1 = Length.Inches(71)
const h2 = Length.convert(h1, 'Centimeter') // h2.value is 180.34000000072135
To normalize an array of possibly nonhomogeneous values, call the static normalize
method:
const lengths = [Length.Inches(71), Length.Meters(0.5), Length.Feet(2.5)]
const lengths_in_cm = Length.normalize(length, 'Centimeter')
TODO