unit-measure
v0.1.2
Published
Class library for managing units of measure and conversions between unit standards.
Downloads
1
Maintainers
Readme
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 = UnitFactory.createUnitObject('tsp', 7)
let asOz = myMeasure.getValueAs('fl.oz')
console.log(`7 teaspoons is ${asOz} fluid ounces`)
- 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 'µ') | | | | | |