unit-measure v0.1.2
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-measureUsage
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
MeasureMeasure The base class of all measure typesRatioRatio The base class of all ratio measurementsUnitTypeUnitType Enumeration of unit typesUnitFactoryUnitFactory Generates a unit type class object by nameNameMapUnitNameMapUnit Synonym maps of common names/abbreviations to unit typesNameMapRatioNameMapRatio Synonym maps of common names/abbreviations to common ratios, plus a Ratio factory methodAccelerationAcceleration MeasuresSpeedoverTimeAmperageAmperage Measures electrical current (e.g. amps)AngleAngle Measures angular span (e.g. degrees, radians)CountCount Measures unit incrementsDensityDensity MeasuresMassperVolumeDistanceDistance Measures distance (e.g. miles, kilometers)FuelEfficiencyFuelEfficiency MeasuresDistanceoverVolumeconsumption (e.g. mpg)LightLight Measures light intensity (e.g. lux)PowerPower Measures power enery (e.g. watts, horsepower)PressurePressure Measures pressure (e.g. lbs/sqIn)SpeedSpeed MeasuresDistanceoverTime(e.g. mph)TemperatureTemperature Measures temperature (e.g. deg F, deg C)TimeTime Measures time (e.g. seconds, minutes, hours, weeks)TorqueTorque Measures torque (e.g. pascals)VoltageVoltage Measures electrical pressure (e.g. volts)VolumeVolume 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
typestring Defines the class of measure (e.g. "distance")baseUnitTypestring The known UnitType that forms the base unit of measurementvaluenumber The initial value to setvalueUnitTypestring? The UnitType of the initial value (if different than base unit)conversionsobject? Conversion table passed by derived type constructors
getValueAs
Returns the current value of the measure in unit terms.
Parameters
unitNamestring Name of unit to return value in.
Returns Number The measure value in the chosen units.
as
Shorthand synonym for getValueAs
Parameters
unitNamestring 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
unitNamestring Name of unit in which to return value. This must always be provided.unitValNumber 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
unitTypestring Abbreviation/token used to specify this unit typeconverter
getConversion
Gets the conversion value for a given unit name
Parameters
unitTypestring The name of the unit.
removeUnit
Removes the unit defined by the given name.
Parameters
unitTypestring 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
Countstring count of physical entitiesEachstring same as CountDozenstring 12 CountScorestring 20 CountBracestring 2 CountPairstring 2 CountKstring 1,000 CountMegstring 1,000,000 CountGigstring 1,000,000,000 CountLuxstring measure of light intensityAmperestring measure of electric currentMilliamperestring measure of small electric currentVoltstring measure of electric voltageMillivoltstring measure of small electric voltageKilovoltstring measure of large electric voltageDegreestring measure angular distanceRadianstring measure angular distance based from piMicrosecondstring measure of very short amount of elapsed timeMillisecondstring measure of short amount of elapsed timeSecondstring measure of an amount of elapsed timeMinutestring measure of an amount of elapsed time equal to 60 secondsHourstring measure of an amount of elapsed time equal to 60 minutesDaystring measure of an amount of elapsed time equal to 24 hoursMontrhstring measure of an amount of elapsed time equal to 1/12th yearYearstring measure of an amount of elapsed time equal to 365 daysCelsiusstring measure of temperature in the metric systemFahrenheitstring measure of temperature in the English systemKelvinstring measure of temperature in terms from "absolute zero" in the metric systemMicrometerstring measure of distance using the metric systemMillimeterstring measure of distance using the metric systemCentimeterstring measure of distance using the metric systemMeterstring measure of distance using the metric systemHectometerstring measure of distance using the metric systemKilometerstring measure of distance using the metric systemOneHundredKmstring measure of distance (100 km) using the metric systemInchstring measure of distance using the US systemFootstring measure of distance using the US systemYardstring -measure of distance using the US systemMilestring measure of distance using the US systemKilopascalstring measure of pressure using the metric systemMegapascalstring measure of pressure using the metric systemPoundsPerSqInstring measure of pressure using the US systemKgPerSqCentimeterstring measure of pressure using the metric systemNewtonMeterstring measure of torque using the metric systemGramForceCentimeterstring measure of torque using the metric systemFootPoundstring measure of torque using the US systemMicroliterstring measure of volume using the metric systemMilliliterstring measure of volume using the metric systemCentiliterstring measure of volume using the metric systemDeciliterstring measure of volume using the metric systemLiterstring measure of volume using the metric systemOuncestring measure of volume using the US systemPintstring measure of volume using the US systemQuartstring measure of volume using the US systemGallonstring measure of volume using the US systemGramstring measure of mass in the metric systemMicrogramstring measure of mass in the metric systemMilligramstring measure of mass in the metric systemKilogramstring measure of mass in the metric systemMetricTonstring measure of mass in the metric systemOuncestring measure of mass in the US systemPoundstring measure of mass in the US systemStonestring measure of mass in old British terminologyImperialTonstring a ton as defined by British Imperial unitsUSTonstring a ton as defined in the USgrainstring measure of mass in old Greek system terminologydramstring measure of mass in old Greek system terminologyTroyOuncestring measure of mass in old Greek system terminologyTroyPoundstring measure of mass in old Greek system terminologyPennyweightstring measure of mass in old Greek and British terminologyKilopascalstring measure of pressure.Megapascalstring measure of pressure.PoundsPerSqInstring measure of pressure.KgPerSqCentimeterstring measure of pressure.NewtonMeterstring measure of torque.GramForceCentimeterstring measure of torque.FootPoundstring measure of torque (US).Literstring measure of volume (metric).Microliterstring measure of volume (metric).Milliliterstring measure of volume (metric).Centiliterstring measure of volume (metric).Deciliterstring measure of volume (metric).FluidOuncestring measure of volume (US).Pintstring measure of volume (US).Quartstring measure of volume (US).Gallonstring measure of volume (US).Teaspoonstring measure of volume (US, recipe).Tablespoonstring measure of volume (US, recipe).Cupstring measure of volume (US, recipe).Dropstring measure of small volume (US, recipe). Defined as equal to 1 milliLiterPinchstring measure of small volume (US, recipe).Dashstring measure of small volume (US, recipe).CubicMeterstring measure of volume (metric).CubicCentimeterstring measure of volume (metric).CubicFootstring measure of volume (US).CubicInchstring measure of volume (US).Wattstring measure of Power.Milliwattstring measure of Power.Kilowattstring measure of Power.Horsepowerstring 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
unitTypeStringinitialValue
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 'µ') | ||||
5 years ago