unit-measure
version: 0.1.2
A class library defining a set of unit-measure types for various styles of measurement, including Ratio type measures such as speed or acceleration.
Purpose:
Define classes of measurement (like Mass, Volume, Length) and an easily extansible mechanism for defining common (or custom) unit measurements within that class so that it is simple to read and write values to/from this type in any of its recognized unit bases. Also maintains a synonym map so that multiple synonymous abbreviated forms may be used interchangeably, and factory operations so that types may be instantiated by name.
Types of measurement.
unit-measure
supports the following measurement types:
Acceleration
(m/sec2, ft/sec2, etc)Amperage
(amps, milliamps, etc.)Angle
(degrees or radians)Count
(simple unit count of items)Distance
(e.g. miles, kilometers)FuelEfficiency
(e.g. mpg, l/100km, etc)Length
(e.g. mm, inch, foot, centimeter, meter, yard)Light
(lux)Mass
(gram, kilogram, ounce, pound, etc)Power
(watt, horsepower)Pressure
(kiloPascal, pounds per sq ft, etc)Speed
(mph, kph, etc.)Time
(microseconds to years)Torque
(Gram Force Centimeter, Foot Pound)Voltage
(Volts)Volume
(liters, fluid ounces, cup, quart, gallon, tsp, tbsp, etc)
Installation
npm install unit-measure
Usage
Simple unit conversion, using the unit class object:
const {UnitType,Volume} = require('unit-measure')
const myMeasure = new Volume()
// Set the measure value in one unit type
myMeasure.setValueAs(3.25, UnitType.tsp)
// read it in a different unit type
let ml = myMeasure.getValueAs(UnitType.MilliLiter)
console.log('There are ${ml} ml in 3.25 tsp')
Using UnitFactory
:
const {UnitType,UnitFactory} = require('unit-measure')
const myMeasure = UnitFactory.createUnitType('teaspoon')
myMeasure.setValue(3.25)
// read it in a different unit type
let ml = myMeasure.getValueAs(UnitType.MilliLiter)
console.log('There are ${ml} ml in 3.25 tsp')
Using Ratios:
const {UnitType, Ratio, NameMapRatio} = require('unit-measure')
// defining a ratio and using it for unit conversion:
const ratio1 = new Ratio('m/s', UniType.Meter, UnitType.Second)
ratio1.setValue(15)
let mph = ratio1.getValueAs(UnitType.Mile, UnitType.Hour)
console.log('traveling at 15 meters/second is equivalent to ${mph} miles/hour`)
// defining a ratio using the NameMapRatio factory:
const ratio2 = NameMapRatio.makeFrom('rpm', 33.33)
let rph = ratio2.getValueAs(UnitType.Count, UnitType.Hour)
console.log(`listening to classic vinyl LPs for an hour means the turntable has rotated ${rph} times`)
Ratio Types:
The Speed
, Density
, FuelEfficiency
and Acceleration
classes
are pre-defined ratios for common ratio measures.
Some of these have 'shortcut' conversion methods for common
purposes (e.g. Speed has getMilesPerHour
, setKilometersPerHour
, etc)
as alternatives to setValueAs
and getValueAs
for common unit
expressions. See the API documentation for more detail.
API
UnitMeasure
Exported APIs of the UnitMeasure library module
Properties
Measure
Measure The base class of all measure typesRatio
Ratio The base class of all ratio measurementsUnitType
UnitType Enumeration of unit typesUnitFactory
UnitFactory Generates a unit type class object by nameNameMapUnit
NameMapUnit Synonym maps of common names/abbreviations to unit typesNameMapRatio
NameMapRatio Synonym maps of common names/abbreviations to common ratios, plus a Ratio factory methodAcceleration
Acceleration MeasuresSpeed
overTime
Amperage
Amperage Measures electrical current (e.g. amps)Angle
Angle Measures angular span (e.g. degrees, radians)Count
Count Measures unit incrementsDensity
Density MeasuresMass
perVolume
Distance
Distance Measures distance (e.g. miles, kilometers)FuelEfficiency
FuelEfficiency MeasuresDistance
overVolume
consumption (e.g. mpg)Light
Light Measures light intensity (e.g. lux)Power
Power Measures power enery (e.g. watts, horsepower)Pressure
Pressure Measures pressure (e.g. lbs/sqIn)Speed
Speed MeasuresDistance
overTime
(e.g. mph)Temperature
Temperature Measures temperature (e.g. deg F, deg C)Time
Time Measures time (e.g. seconds, minutes, hours, weeks)Torque
Torque Measures torque (e.g. pascals)Voltage
Voltage Measures electrical pressure (e.g. volts)Volume
Volume Measures units of volume (e.g liter, gallon)
Measure
Base class of the unit-measure types.
Methods include facilities for measurement conversion.
####### Properties
name | type | description |
---|---|---|
measureType |
string | name of this measure type |
unitTable |
Map<string, Converter> | key/value map of units to conversions factors |
baseUnit |
string | name or abbreviation of unit type this conversion applies to |
Constructor
Parameters
type
string Defines the class of measure (e.g. "distance")baseUnitType
string The known UnitType that forms the base unit of measurementvalue
number The initial value to setvalueUnitType
string? The UnitType of the initial value (if different than base unit)conversions
object? Conversion table passed by derived type constructors
getValueAs
Returns the current value of the measure in unit terms.
Parameters
unitName
string Name of unit to return value in.
Returns Number The measure value in the chosen units.
as
Shorthand synonym for getValueAs
Parameters
unitName
string Name of unit to return value in.
Returns Number The measure value in the chosen units.
getValue
Returns the value in terms of the current value unit.
setValueAs
Sets the value of this measure in unit terms
Parameters
unitName
string Name of unit in which to return value. This must always be provided.unitVal
Number Value in unit terms to which to set the measure value.
getBaseUnit
Returns the base unit UnitType.
Returns string base unit token string defined for this Measure
getValueUnit
Returns the UnitType the current value was last set with
addUnit
Adds a name describing a unit and the conversion from standard measure for this unit.
The name should come from the UnitType declared values.
The conversion function is a supplied function that takes two parameters (to, from), but only one at a time. The first parameter ("to") will be undefined if the second parameter ("from") is to be used. Passing a value for "to" means that the given value in base units should be converted to the named unit. Passing a value for "from" means that the given value in named units should be converted to base units.
The supplied function should perform the to/from conversions as appropriate for the type and return the result.
Use this to supply new units with Converter functions. Use addConversions to supply new units with scale factors
Parameters
unitType
string Abbreviation/token used to specify this unit typeconverter
getConversion
Gets the conversion value for a given unit name
Parameters
unitType
string The name of the unit.
removeUnit
Removes the unit defined by the given name.
Parameters
unitType
string The name of the unit.
clearUnits
Removes all unit definitions.
getUnits
Returns the array of unitType names this Measure type supports conversion for
addConversions
Adds the table of conversions to unit table Table can contain scale factors or Converter functions
Parameters
conversions
UnitType
Contains the canonical text tag abbreviations for UnitType values. See NameMapUnit for a list of recognized synonyms for each canonical type.
These text tags are intentionally equivalent to the common abbreviated version of the
unit name that can be found in NameMapUnit
Properties
Count
string count of physical entitiesEach
string same as CountDozen
string 12 CountScore
string 20 CountBrace
string 2 CountPair
string 2 CountK
string 1,000 CountMeg
string 1,000,000 CountGig
string 1,000,000,000 CountLux
string measure of light intensityAmpere
string measure of electric currentMilliampere
string measure of small electric currentVolt
string measure of electric voltageMillivolt
string measure of small electric voltageKilovolt
string measure of large electric voltageDegree
string measure angular distanceRadian
string measure angular distance based from piMicrosecond
string measure of very short amount of elapsed timeMillisecond
string measure of short amount of elapsed timeSecond
string measure of an amount of elapsed timeMinute
string measure of an amount of elapsed time equal to 60 secondsHour
string measure of an amount of elapsed time equal to 60 minutesDay
string measure of an amount of elapsed time equal to 24 hoursMontrh
string measure of an amount of elapsed time equal to 1/12th yearYear
string measure of an amount of elapsed time equal to 365 daysCelsius
string measure of temperature in the metric systemFahrenheit
string measure of temperature in the English systemKelvin
string measure of temperature in terms from "absolute zero" in the metric systemMicrometer
string measure of distance using the metric systemMillimeter
string measure of distance using the metric systemCentimeter
string measure of distance using the metric systemMeter
string measure of distance using the metric systemHectometer
string measure of distance using the metric systemKilometer
string measure of distance using the metric systemOneHundredKm
string measure of distance (100 km) using the metric systemInch
string measure of distance using the US systemFoot
string measure of distance using the US systemYard
string -measure of distance using the US systemMile
string measure of distance using the US systemKilopascal
string measure of pressure using the metric systemMegapascal
string measure of pressure using the metric systemPoundsPerSqIn
string measure of pressure using the US systemKgPerSqCentimeter
string measure of pressure using the metric systemNewtonMeter
string measure of torque using the metric systemGramForceCentimeter
string measure of torque using the metric systemFootPound
string measure of torque using the US systemMicroliter
string measure of volume using the metric systemMilliliter
string measure of volume using the metric systemCentiliter
string measure of volume using the metric systemDeciliter
string measure of volume using the metric systemLiter
string measure of volume using the metric systemOunce
string measure of volume using the US systemPint
string measure of volume using the US systemQuart
string measure of volume using the US systemGallon
string measure of volume using the US systemGram
string measure of mass in the metric systemMicrogram
string measure of mass in the metric systemMilligram
string measure of mass in the metric systemKilogram
string measure of mass in the metric systemMetricTon
string measure of mass in the metric systemOunce
string measure of mass in the US systemPound
string measure of mass in the US systemStone
string measure of mass in old British terminologyImperialTon
string a ton as defined by British Imperial unitsUSTon
string a ton as defined in the USgrain
string measure of mass in old Greek system terminologydram
string measure of mass in old Greek system terminologyTroyOunce
string measure of mass in old Greek system terminologyTroyPound
string measure of mass in old Greek system terminologyPennyweight
string measure of mass in old Greek and British terminologyKilopascal
string measure of pressure.Megapascal
string measure of pressure.PoundsPerSqIn
string measure of pressure.KgPerSqCentimeter
string measure of pressure.NewtonMeter
string measure of torque.GramForceCentimeter
string measure of torque.FootPound
string measure of torque (US).Liter
string measure of volume (metric).Microliter
string measure of volume (metric).Milliliter
string measure of volume (metric).Centiliter
string measure of volume (metric).Deciliter
string measure of volume (metric).FluidOunce
string measure of volume (US).Pint
string measure of volume (US).Quart
string measure of volume (US).Gallon
string measure of volume (US).Teaspoon
string measure of volume (US, recipe).Tablespoon
string measure of volume (US, recipe).Cup
string measure of volume (US, recipe).Drop
string measure of small volume (US, recipe). Defined as equal to 1 milliLiterPinch
string measure of small volume (US, recipe).Dash
string measure of small volume (US, recipe).CubicMeter
string measure of volume (metric).CubicCentimeter
string measure of volume (metric).CubicFoot
string measure of volume (US).CubicInch
string measure of volume (US).Watt
string measure of Power.Milliwatt
string measure of Power.Kilowatt
string measure of Power.Horsepower
string measure of Power.
UnitFactory
Contains the factory function createUnitObject
which is able to construct a unit-measure type by its name/abbreviation.
This is handy when creating units after having parsed a value and its type, as most commonly used notations are supported.
createUnitObject
Creates a unit of the given type
Parameters
unitTypeString
initialValue
Examples
let myMeasure = UnitFactorylet asOz = myMeasureconsole
- Throws Error if unit type is unknown
Returns Measure
NameMapUnit
Maps common synonyms for UnitType values to the canonical UnitType. Includes resolveSynonym, setMeasureAs, and getMeasureAs utility functions.
Note that all the terms used here are in lower case, but are in fact case-insensitive. In other words ('km' and 'Km' and 'KM' are all equivalent)
Measure type Class | abbr. | name/desc | |||
---|---|---|---|---|---|
Count | Unit types Count: to indicate or name by units or groups so as to find the total number of units involved | ||||
count | name for all item types | ||||
ea | Each (item) | ||||
each | Each (item) | ||||
level | may identify a count for a level or rank | ||||
percentage | may identify a count in a percentage ratio | ||||
percentage | may identify a count in a percentage ratio | ||||
percent | may identify a count in a percentage ratio | ||||
pct | may identify a count in a percentage ratio | ||||
% | may identify a count in a percentage ratio | ||||
Light | Measurement of light intensity (Lux) Lux: The amount of light that is cast on a surface is called illuminance, which is measured in lux. This can be thought of as light intensity within a specific area. Lumens: The total output of visible light from a light source is measured in lumens. ... One lux is equal to one lumen per square meter (lux = lumens/m2) | ||||
lux | Measure of light intensity | ||||
Ampere | Measurement of electrical current: An international System of units (SI) term. | ||||
amp | meaning 1 ampere | ||||
milliampere | 1/1000 of an ampere | ||||
milliamp | 1/1000 of an amp | ||||
milliamps | optional plural of same | ||||
ma | Abbreviation for milliamp | ||||
Volt | Measurement of electrical potential when measured at 1 ampere with a resistance of 1 ohm | ||||
voltage | Volt | ||||
volt | Volt | ||||
volts | optional plural of same | ||||
v | Abbreviation of volt | ||||
kilovolt | 1000 volts | ||||
kv | Abbreviation of kilovolt | ||||
millivolt | 1/1000 volts | ||||
mv | Abbreviation of millivolt | ||||
mvolt | Abbreviation of millivolt | ||||
Power | Measurement of Power: a source or means of supplying energy | ||||
horsepower | Defined originally as the power of a pulling horse. | ||||
hp | Abbreviation of horsepower | ||||
watt | power produced by a current of one ampere across a potential difference of one volt | ||||
w | Abbreviation of watt | ||||
milliwatt | 1/1000 watt | ||||
kilowatt | 1000 watts | ||||
mw | Abbreviation of milliwatt | ||||
kw | Abbreviation of kilowatt | ||||
Angle | Measure of separation of two vectors; the amount of turning necessary to bring one line or plane into coincidence with or parallel to another | ||||
degree | Term of measurement of an angle where 360 degrees comprise a full rotation. | ||||
radian | Term of measurement of an angle that is equal to the angle at the center of a circle subtended by an arc whose length equals the radius or approximately 57.3 degrees | ||||
radians | optional plural of same | ||||
angle | Used as a synonym for 'degree' | ||||
angular degrees | Used as a synonym for 'degree' | ||||
angulardegrees | Used as a synonym for 'degree' (for certain coding purposes) | ||||
deg | Abbreviation for 'degree' | ||||
rad | Abbreviation for 'radian' | ||||
Time | Measurements of duration or interval | ||||
time | base type for time is the 'second' | ||||
second | a unit of time we are all familiar with | ||||
seconds | optional plural of same | ||||
microsecond | one millionth of a second | ||||
millisecond | one thousandth of a second | ||||
us | Abbreviation for microsecond (derived from µs, substituting ASCII 'u' for 'µ') | ||||
ms | Abbreviation for millisecond | ||||
sec | Abbreviation for Second | ||||
minute | a unit of time we are all familiar with. Equal to 60 seconds | ||||
minutes | optional plural of same | ||||
min | Abbreviation for Minute | ||||
hour | a unit of time we are all familiar with. Equal to 60 minutes | ||||
hours | optional plural of same | ||||
hr | Abbreviation of hour | ||||
day | a unit of time we are all familiar with. Equal to 24 hours | ||||
days | optional plural of same | ||||
dy | Abbreviation of day | ||||
month | a unit of time we are all familiar with. Equal to 1/12 Year. Note: not all months are equivalent. This is a generalized average. | ||||
months | optional plural of same | ||||
mo | Abbreviation of month | ||||
year | a unit of time we are all familiar with. Equal to 365 days. Note that technically a year is 365.25 days, but much like in the case of months, this is simplified for duration purposes. | ||||
years | optional plural of same | ||||
yr | Abbreviation of year | ||||
Tenperature | Measurement of the warmth or coldness of an object or substance with reference to some standard value. | ||||
degrees celsius | metric and SI standard for temperature measurement worldwide. | ||||
celsius | Synonym for 'degrees celsius' | ||||
degreescelsius | Synonym for 'degrees celsius' (for certain coding purposes) | ||||
degrees c | Synonym for 'degrees celsius' | ||||
celsius | Synonym for 'degrees celsius' | ||||
centigrade | * | degrees celsius | metric and SI standard for temperature measurement worldwide. | ||
fahrenheit | syonymous with degrees fahrenheit | ||||
degrees fahrenheit | imperial system of measurement still standard in the US and its territories. | ||||
degrees f | syonymous with degrees fahrenheit | ||||
f | Abbreviation for degrees fahrenheit | ||||
kelvin | Kelvin system of measurement, used in scientific contexts, where 0 represents 'absolute zero' (no atomic action). Unlike the degree Fahrenheit and degree Celsius, the kelvin is not referred to or written as a degree. The kelvin is the primary unit of temperature measurement in the physical sciences, but is often used in conjunction with the degree Celsius, which has the same magnitude. | ||||
klv | Abbreviation for Kelvin | ||||
Length | Measurement of size and local distance. Overlaps "Distance" in terms of scale. Prefer Length for sub-kilometer measures. | ||||
length | base unit of Length is the Meter | ||||
meter | The SI and metric standard used for measurement (except US) | ||||
meters | optional plural of same | ||||
m | Abbreviation for meter | ||||
decimeter | 1/10th of a meter | ||||
decimeters | optional plural of same | ||||
dm | Abbreviation for decimeter | ||||
centimeter | 1/100th of a meter | ||||
centimeters | optional plural of same | ||||
cm | Abbreviation for centimeter | ||||
millimeter | 1/1000th of a meter | ||||
millimeters | optional plural of same | ||||
mm | Abbreviation for millimeter | ||||
micometer | one millionth of a meter | ||||
micometers | optional plural of same | ||||
um | Abbreviation for micometer | ||||
hectometer | 100 meters | ||||
hectometers | optional plural of same | ||||
hm | Abbreviation for hectometer | ||||
inch | US Inch | ||||
inches | optional plural of same | ||||
foot | US Foot. Equivalent to a dozen (12) inches. | ||||
feet | optional plural of same | ||||
ft | Abbreviation for foot | ||||
yard | US yard. Equivalent to 3 feet. | ||||
yards | optional plural of same | ||||
yd | Abbreviation for yard | ||||
Distance | Measurement of distances. Overlaps Length in terms of scale. Prefer Distance for Kilometer and above. | ||||
distance | base type for distance is the kilometer. | ||||
kilometer | Metric and SI standard for distance measurement | ||||
kilometers | optional plural of same | ||||
km | Abbreviation for kilometer | ||||
100km | One hundred Kilometers | ||||
one humdred kilometers | Synonym for 100km | ||||
onehumdredkilometers | Synonym for 100km | ||||
100 kilometers | Synonym for 100km | ||||
onehumdredkm | Synonym for 100km | ||||
100 km | Synonym for 100km | ||||
mile | US Mile measurement for distance (about 2.2 kilometers) | ||||
miles | optional plural of same | ||||
mi | Abbreviation for mile | ||||
Volume | Measure of occupied space | ||||
volume | The base type for Volume is the Liter | ||||
liter | The metric and SI standard for volume measurement | ||||
liters | optional plural of same | ||||
l | Abbreviation for liter | ||||
microliter | one millionth of a liter | ||||
microliters | optional plural of same | ||||
ul | Abbreviation for microliter (derived from µl, substituting ASCII 'u' for 'µ') | ||||
milliliter | 1/1000th liter | ||||
milliliters | optional plural of same | ||||
cubic centimeter | equivalent to milliliter | ||||
cm3 | Abbreviation for cubic centimeter | ||||
cc | Abbreviation for cubic centimeter | ||||
ml | Abbreviation for milliliter | ||||
centiliter | 1/100th liter | ||||
centiliters | optional plural of same | ||||
cl | Abbreviation of centiliter | ||||
deciliter | one tenth liter | ||||
deciliters | optional plural of same | ||||
dl | Abbreviation for deciliter | ||||
fluid ounce | US Unit of measure | ||||
fluid ounces | optional plural of same | ||||
fluidounce | synonym for FLuid ounce (for certain coding purposes) | ||||
fl ounce | Abbreviation for Fluid Ounce | ||||
fl. ounce | Abbreviation for Fluid Ounce | ||||
fl. ounces | optional plural of same | ||||
fl oz | Abbreviation for Fluid Ounce | ||||
floz | Abbreviation for Fluid Ounce | ||||
fl. oz | Abbreviation for Fluid Ounce | ||||
fl. ounce | Abbreviation for Fluid Ounce | ||||
fl.oz | Abbreviation for Fluid Ounce | ||||
pint | US Unit of measure | ||||
pints | optional plural of same | ||||
pt | Abbreviation for Pint | ||||
quart | US Unit of measure | ||||
quarts | optional plural of same | ||||
qt | Abbreviation for quqrt | ||||
gallon | US Unit of measure | ||||
gallons | optional plural of same | ||||
gal | Abbreviation of gallon | ||||
teaspoon | US kitchen measure unit | ||||
tsp | Abbreviation for teaspoon | ||||
t | Abbreviation for teaspoon | ||||
tablespoon | US kitchen measure unit | ||||
tbsp | Abbreviation for tablespoon | ||||
tb | Abbreviation for tablespoon | ||||
cup | US kitchen measure unit | ||||
c | Abbreviaion for cup | ||||
drop | Colloquial measurement | ||||
drip | synonym for drop | ||||
drp | Abbreviation for drop | ||||
pinch | Colloquial measurement | ||||
pch | Abbreviation for pinch | ||||
dash | Colloquial measurementa | ||||
dsh | Abbreviation for dash | ||||
cubic meter | Cubic meter | ||||
cubicmeter | Synonym fro cubic meter | ||||
m3 | Abbreviation for cubic meter | ||||
cubic centimeter | Cubic centimeter (see also milliliter) | ||||
cubiccentimeter | Synonym for cubic centimeter | ||||
cubic foot | US cubic foot | ||||
cubicfoot | Synonym for cubic foot | ||||
ft3 | Abbreviation for cubic feet | ||||
cft | Abbreviation for cubic feet | ||||
cf | Abbreviation for cubic feet | ||||
cubic inch | US cubic inch | ||||
cubicinch | Synonym for cubic inch | ||||
ci | Abbreviation for cubic inch | ||||
cin | Abbreviation for cubic inch | ||||
Mass | Mass is commonly known as weight, although this is incorrect. An object's mass determines the strength of its gravitational attraction to other bodies, such as the earth. The force of this attraction is characterized as weight. For common terrestrial meaning, mass and weight are close enough to be synonymous. | ||||
mass | the base unit for mass measurement is the gram | ||||
gram | the metric and SI standard for mass measurement. | ||||
g | Abbreviation for gram | ||||
microgram | one millionth of a gram | ||||
mcg | Abbreviation of microgram | ||||
ug | Abbreviation of microgram (derived from µg, substituting ASCII 'u' for 'µ') | ||||
milligram | 1/1000th of a gram | ||||
mg | Abbreviation of milligram | ||||
kilogram | 1000 grams | ||||
kg | Abbreviation of kilogram | ||||
ounce | US measure of weight. 1/16 Pound | ||||
ounces | optional plural form of same | ||||
oz | Abbreviation of ounce | ||||
ozs | optional plural form of same | ||||
pound | US Standard weight measure | ||||
pounds | optional plural form of same | ||||
lb | Abbreviation for pound | ||||
lbs | optional plural form of same | ||||
stone | archaic imperial measure | ||||
st | Abbreviaiton for stone | ||||
metric ton | metric and SI definition of a 'ton' | ||||
metricton | synonym for metric ton | ||||
tonne | synonym for metric ton | ||||
mton | Abbreviation for metric ton | ||||
mt | Abbreviation for metric ton | ||||
imperial ton | British Imperial definitio of 'ton' | ||||
imperialton | synonym for imperial ton | ||||
iton | Abbreviation for imperial ton | ||||
long ton | synonym for Imperial ton | ||||
longton | synonym for long ton | ||||
l. ton | Abbreviation for long ton | ||||
l.ton | Abbreviation for long ton | ||||
l. tn | Abbreviation for long ton | ||||
l.tn | Abbreviation for long ton | ||||
ltn | Abbreviation for long ton | ||||
us ton | US definition for 'ton' | ||||
uston | synonym for US Ton | ||||
short ton | synonym for US Ton | ||||
shortton | synonym for Short Ton | ||||
sh, ton | synonym for Short Ton | ||||
sh.ton | synonym for Short Ton | ||||
sh. tn | synonym for Short Ton | ||||
sh.tn | synonym for Short Ton | ||||
shtn | synonym for Short Ton | ||||
grain | Archaic measurement of small masses (Greek / British) | ||||
gr | Abbreviation for grain | ||||
dram | Archaic measurement of small masses (Greek / British) | ||||
dr | Abbreviation for dram | ||||
troy ounce | Archaic weight measurement (Greek / British) | ||||
troyounce | synonym for troy ounce | ||||
oz t | Abbreviation for troy ounce | ||||
ozt | Abbreviation for troy ounce | ||||
troy pound | Archaic weight measurement (Greek / British) | ||||
troypound | synonym for troy pound | ||||
lb t | Abbreviation for troy pound | ||||
lbt | Abbreviation for troy pound | ||||
pennyweight | Archaic weight measurement (Greek / British) | ||||
dwt | Abbreviation for pennyweight | ||||
pwt | Abbreviation for pennyweight | ||||
pw | Abbreviation for pennyweight | ||||
Pressure | Pressure is defined as the physical force exerted on an object. | ||||
pressure | The base unit of pressure is the kilopascal (Kpa) | ||||
kilopascal | The SI standard for pressure measurement. | ||||
kpa | Abbreviation for kilopascal | ||||
megapascal | 1000 Kpa | ||||
mpa | Abbreviation for megapascal | ||||
pounds per square inch | US unit measure if si many pounds per square inch of surface area | ||||
poundspersquqreinch | synonyn for pounds per square inch | ||||
poundspersqin | Abbreviation for pounds per square inch | ||||
psi | Abbreviation for pounds per square inch | ||||
lb/in2 | Abbreviation for pounds per square inch | ||||
kg per square centimeter | Pressure of so many kilograms per square centimeter of surface area | ||||
kgpersquarecentimeter | Synonym for kg per square centimeter | ||||
kgpersqcentimeter | Synonym for kg per square centimeter | ||||
kg/cm2 | Abbreviation for kg per square centimeter | ||||
Torque | Torque is the rotational equivalent of linear force. It is also referred to as the moment, moment of force, rotational force or turning effect, depending on the field of study. | ||||
torque | The Newton Meter is the SI standard unit of torque | ||||
newton meter | The Newton Meter is the SI standard unit of torque\ | ||||
newtonmeter | Synonymous with newton meter | ||||
nm | Abbreviation of Newton Meter | ||||
gram force centimeter | Alternative measure of torque | ||||
gram-force centimeter | Synonym to gram force centimeter | ||||
gram force cm | Synonym to gram force centimeter | ||||
gram-force cm | Synonym to gram force centimeter | ||||
gfcm | Abbreviation for gram force centimeter | ||||
gf*cm | Abbreviation for gram force centimeter | ||||
foot pound | US measure of torque | ||||
footpound | Synonym to foot pound | ||||
ft lbs | Abbreviation for foot pound | ||||
lbft | Abbreviation for foot pound | ||||
pound-force foot | Synonym to foot pound |
resolveSynonym
Finds the canonical UnitType measure for one of the mapped synonyms
Parameters
unitIn
string Unit string to match to a canonical UnitType
Examples
let abbrevIn = 'cf' let canonType = NameMapUnit // canonType === UnitType.CubicFoot === 'ft3'
Returns string Equivalent UnitType, or undefined
setMeasureAs
Sets the provided Measure value with a new value expressed in a value that may be a synonym
Parameters
measure
{Measure} The Measure object to setunitIn
{string} The unit to match to a canonical UnitType and set value asvalue
{number} The value to set
Examples
let myMeasure = NameMapUnit
getMeasureAs
Returns the value of the provided Measure in units expressed by the resolved synonym
Parameters
measure
{Measure} The Measure object to readunitIn
{string} The unit to match to a canonical UnitType for value
Examples
: let myMeasure = UnitTypeInch 27 let feet = NameMapUnit
Returns number The value of this measure in resolved UnitType
Ratio
Defines a Ratio of two Measure units. Common examples: Speed, Density, FuelEfficiency. Can be used for any number of arbitrary associations
Constructor
Parameters
ratioType
measure1
measure2
numVal
denVal
setRatioValues
Set the ratio values independently.
Parameters
value1
measure1Type
value2
measure2Type
getValueAs
Returns the ratio in terms of the measure types given.
For example, for a Ratio set up with a Distance and a Time measure, passing UnitType Kilometer, UnitType Hour would give the speed in Kilometers per Hour
Parameters
measure1Type
UnitTypemeasure2Type
UnitType
Returns number
NameMapRatio
Lookup table for common measurements and their associated compositions
Basic Ratios
common abbr. | full name | instance type | numerator unit | denominator unit |
---|---|---|---|---|
ratio | generic ratio | Ratio | UnitType.Count | UnitType.Count |
deg/sec | degrees per second | Ratio | UnitType.Degree | UnitType.Second |
rpm | revolutions per minute | Ratio | UnitType.Count | UnitType.Minute |
Densities
common abbr. | full name | instance type | numerator unit | denominator unit |
---|---|---|---|---|
g/cc | grams per cubic centimeter | Density | UnitType.Gram | UnitType.Milliliter |
g/ml | grams per milliliter | Density, UnitType.Gram | UnitType.Milliliter | |
kg/l | kilograms per liter | Density, UnitType.Kilogram | UnitType.Liter | |
oz/fl.oz | ounces per fluid ounce | Density | UnitType.Ounce | UnitType.FluidOunce |
lb/gal | pounds per gallon | Density, UnitType.Pound | UnitType.Gallon] | |
g/tsp | grams per teaspoon | Density, UnitType.Gram | UnitType.Teaspoon | |
g/tbsp | grams per tablespoon | Density | UnitType.Gram | UnitType.Tablespoon |
speeds
common abbr. | full name | instance type | numerator unit | denominator unit |
---|---|---|---|---|
mph | miles per hour | Speed | UnitType.Mile | UnitType.Hour |
kph | kilometers per hour | Speed | UnitType.Kilometer | UnitType.Hour |
mps | meters per second | Speed | UnitType.Meter | UnitType.Second |
fps | feet per second | Speed | UnitType.Foot | UnitType.Second |
Fuel Efficiencies
common abbr. | full name | instance type | numerator unit | denominator unit |
---|---|---|---|---|
mpg | miles per gallon | FuelEfficiency | UnitType.Mile | UnitType.Gallon |
kpg | kilometers per gallon | FuelEfficiency | UnitType.Kilometer | UnitType.Gallon |
kpl | kilometers per liter | FuelEfficiency | UnitType.Kilometer | UnitType.Liter |
mpl | meters per liter | FuelEfficiency | UnitType.Meter | UnitType.Liter |
l/100km | liters per 100km | FuelEfficiency | UnitType.OneHundredKm | UnitType.Liter |
Accelerations
common abbr. | full name | instance type | numerator unit | denominator unit |
---|---|---|---|---|
m/s2 | meters per second squared | Acceleration | UnitType.Meter | UnitType.Second |
mps/sec | meters per second squared | Acceleration | UnitType.Meter | UnitType.Second |
ft/s2 | feet per second squared | Acceleration | UnitType.Foot | UnitType.Second |
fps/sec | feet per second squared | Acceleration | UnitType.Foot | UnitType.Second |
makeFrom
Creates an appropriate compound Measure Ratio object for the given name and values
Parameters
ratioName
string Name of the ratio to match tovalue1
number Value of the ratio, or the value of the numeratorvalue2
number Value of the denominator or undefined - to avoid a dangerous division by zero (optional, default1
)
Examples
let mySpeed = NameMapRatio let myMPG = NameMapRatio mySpeed // 60 myMPG // 27.59
Returns Ratio
Acceleration
Ratio designed for Acceleration: (speed over time)
Constructs an Acceleration Ratio object Default acceleration units are in m/sec2
Constructor
Parameters
distType
string? distance type, default 'm'timeType
string? duration of time, default 'sec'distValue
number? value for distance, default 0timeValue
number? value for time, default 1
getMetersPerSecondSquared
Returns this Acceleration value in meters per second per second (m/sec2)
Returns number
setMetersPerSecondSquared
Sets this Acceleration value in meters per second per second (m/s2)
Parameters
mps2
number acceleration (m/s2)
getFeetPerSecondSquared
Returns this Acceleration value in feet per second per second (ft/s2)
Returns number
setFeetPerSecondSquared
Sets this Acceleration value in feet per second per second (ft/s2)
Parameters
fps2
number acceleration (ft/s2)
setValueAs
Sets this Acceleration value expressed as a specific distance and time unit ratio.
Parameters
value
number The value to setratioType
string The ratio type unit identifier this value is based on
setRatioValues
Sets this Acceleration value expressed as separate distance and time values as a fraction.
Parameters
Amperage
Defines measure for Electric Current. UnitType Amperage is the base unit.
Constructor
Parameters
Angle
Defines measure for Angles. UnitType Degree is the base unit.
Constructor
Parameters
Count
Defines measure for counting. UnitType Count is the base unit.
Constructor
Parameters
value
number? numeric value representation
Density
Constructs a Ratio for mass / volume Default unit pair is gram/cubic centimeter (aka gram/milliLiter)
Constructor
Parameters
massType
string? The unit type for mass (default 'g')volumeType
string? The unit type for volume (default 'cc')massValue
number The value for distance or speed (default 0) (optional, default0
)volumeValue
number The value for time (default 1) (optional, default1
)
Distance
Distance measure. Used for long distances. Compatible with Length. Sets up units for Centimeter, Decimeter, Meter, Hectometer, Kilometer, Inch, Foot, Yard, Mile
Constructor
Parameters
FuelEfficiency
Defines a Ratio for FuelEfficiency as distance / volume Default is km/l
Contains helper methods for common conversions.
Constructor
Parameters
distanceType
string? default 'km'volumeType
string? default 'l'distanceValue
number? default 1volumeValue
number? default 0
getMilesPerGallon
Returns this FuelEfficiency value in Miles Per Gallon
Returns number
setMilesPerGallon
Sets this FuelEfficiency value in terms of Miles Per Gallon
Parameters
mpg
getKilometersPerLiter
Returns this FuelEfficiency value in Kilometers per Liter
Returns number
setKilometersPerLiter
Sets this FuelEfficiency value in terms of Kilometers Per Liter
Parameters
kpl
getLitersPerKm
Gets liters consumed per kilometer
Returns number
setLitersPerKm
Sets liters per kilometer
Parameters
l
getLitersPer100Km
Returns this FuelEfficiency value in Liters per 100 Kilometers
Returns number
setLitersPer100Km
Sets this FuelEfficiency value in terms of Liters Per 100 Kilometers
Parameters
lphkm
getMillilitersPer100Km
Returns this FuelEfficiency value in Milliliters per 100 Kilometers
Returns number
setMillilitersPer100Km
Sets this FuelEfficiency value in terms of Milliliters per 100 Kilometers
Parameters
mlphkm
Length
Defines measure for Length. UnitType Meter is the base unit.
Constructor
Parameters
Light
Defines measure for light intensity. UnitType Lux is the base unit.
Constructor
Parameters
Mass
Defines measure for mass. UnitType Gram is the base unit.
Constructor
Parameters
Power
Defines measure for Power. UnitType Watt is the base unit.
Constructor
Parameters
Pressure
Defines measure for Pressure. UnitType Kilopascal is the base unit.
Constructor
Parameters
Speed
Constructs a Ratio for distance / time
Constructor
Parameters
distType
string? The unit type for distance (default 'km')timeType
string? The unit type for time (default 'hr')distValue
number The value for distance or speed (default 0) (optional, default0
)timeValue
number The value for time (default 1) (optional, default1
)
getKilometersPerHour
Returns this Speed value in kilometers per hour
Returns number
setKilometersPerHour
Sets this Speed value in Kilometers per hour
Parameters
kph
number
getMilesPerHour
Returns this Speed value in miles per hour
Returns number
setMilesPerHour
Sets this Speed value in Miles per hour
Parameters
mph
number
Temperature
Defines measure for Temperature. UnitType Celsius is the base unit.
Contains functions for common conversions.
Constructor
Parameters
Time
Defines measure for Time. UnitType Second is the base unit.
Constructor
Parameters
Torque
Defines measure for Torque. UnitType NewtonMeter is the base unit.
Constructor
Parameters
Voltage
Defines measure for Electric Voltage. UnitType Volt is the base unit.
Constructor
Parameters
Volume
Defines measure for Volume. UnitType Liter is the base unit.
Constructor
Parameters
Contributing
We welcome and encourage contribution! That's what open-source sharing is all about, right?
Corrections
If you find errors in conversions, abbreviations, or other elements of this library implementation, please post an issue immediately.
Post using the label bug
and be as specific as you can.
Code examples showing the problem are recommended if possible.
Bugs can be submitted to the issues page
Suggestions
If you have suggestions for expanding or improving this library, please
post your ideas to the issues page.
Use the enhancement
or documentation
label, depending on your suggestion type.
Code contribution
If you are browsing the issues page, and see something that you think you can support in code, then please fork the github repo, make and test your changes, then submit as a Pull Request. Reference the issue # that your change represents in the submission. If you are unsure about how to prepare a Pull Request, please read this GitHub doc.
Use case scenarios
If you are using this in your application, please drop us a line telling us your use case and context. This will help us to improve this and other offerings by understanding who uses our work and why.
You can post your feedback to the issues page (please use
the label tag other
), or you can email me directly at mailto:steve@ohmert.com
License
unit-measure is 100% free and open-source per the MIT License. Use it however you want. If you find this module useful, please mention it in your credits, readmes, blogs, etc.
Reaching out
I'd also love to hear from you. Please feel free to email me at mailto:steve@ohmert.com or message me on Twitter @tremho1