New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

unit-measure

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

unit-measure

Class library for managing units of measure and conversions between unit standards.

latest
Source
npmnpm
Version
0.1.2
Version published
Maintainers
1
Created
Source

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.

Build Status NPM version Downloads TotalDownloads Twitter Follow

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 types
  • Ratio Ratio The base class of all ratio measurements
  • UnitType UnitType Enumeration of unit types
  • UnitFactory UnitFactory Generates a unit type class object by name
  • NameMapUnit NameMapUnit Synonym maps of common names/abbreviations to unit types
  • NameMapRatio NameMapRatio Synonym maps of common names/abbreviations to common ratios, plus a Ratio factory method
  • Acceleration Acceleration Measures Speed over Time
  • Amperage Amperage Measures electrical current (e.g. amps)
  • Angle Angle Measures angular span (e.g. degrees, radians)
  • Count Count Measures unit increments
  • Density Density Measures Mass per Volume
  • Distance Distance Measures distance (e.g. miles, kilometers)
  • FuelEfficiency FuelEfficiency Measures Distance over Volume 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 Measures Distance over Time (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

nametypedescription
measureTypestringname of this measure type
unitTableMap<string, Converter>key/value map of units to conversions factors
baseUnitstringname 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 measurement
  • value number The initial value to set
  • valueUnitType 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 type
  • converter
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 entities
  • Each string same as Count
  • Dozen string 12 Count
  • Score string 20 Count
  • Brace string 2 Count
  • Pair string 2 Count
  • K string 1,000 Count
  • Meg string 1,000,000 Count
  • Gig string 1,000,000,000 Count
  • Lux string measure of light intensity
  • Ampere string measure of electric current
  • Milliampere string measure of small electric current
  • Volt string measure of electric voltage
  • Millivolt string measure of small electric voltage
  • Kilovolt string measure of large electric voltage
  • Degree string measure angular distance
  • Radian string measure angular distance based from pi
  • Microsecond string measure of very short amount of elapsed time
  • Millisecond string measure of short amount of elapsed time
  • Second string measure of an amount of elapsed time
  • Minute string measure of an amount of elapsed time equal to 60 seconds
  • Hour string measure of an amount of elapsed time equal to 60 minutes
  • Day string measure of an amount of elapsed time equal to 24 hours
  • Montrh string measure of an amount of elapsed time equal to 1/12th year
  • Year string measure of an amount of elapsed time equal to 365 days
  • Celsius string measure of temperature in the metric system
  • Fahrenheit string measure of temperature in the English system
  • Kelvin string measure of temperature in terms from "absolute zero" in the metric system
  • Micrometer string measure of distance using the metric system
  • Millimeter string measure of distance using the metric system
  • Centimeter string measure of distance using the metric system
  • Meter string measure of distance using the metric system
  • Hectometer string measure of distance using the metric system
  • Kilometer string measure of distance using the metric system
  • OneHundredKm string measure of distance (100 km) using the metric system
  • Inch string measure of distance using the US system
  • Foot string measure of distance using the US system
  • Yard string -measure of distance using the US system
  • Mile string measure of distance using the US system
  • Kilopascal string measure of pressure using the metric system
  • Megapascal string measure of pressure using the metric system
  • PoundsPerSqIn string measure of pressure using the US system
  • KgPerSqCentimeter string measure of pressure using the metric system
  • NewtonMeter string measure of torque using the metric system
  • GramForceCentimeter string measure of torque using the metric system
  • FootPound string measure of torque using the US system
  • Microliter string measure of volume using the metric system
  • Milliliter string measure of volume using the metric system
  • Centiliter string measure of volume using the metric system
  • Deciliter string measure of volume using the metric system
  • Liter string measure of volume using the metric system
  • Ounce string measure of volume using the US system
  • Pint string measure of volume using the US system
  • Quart string measure of volume using the US system
  • Gallon string measure of volume using the US system
  • Gram string measure of mass in the metric system
  • Microgram string measure of mass in the metric system
  • Milligram string measure of mass in the metric system
  • Kilogram string measure of mass in the metric system
  • MetricTon string measure of mass in the metric system
  • Ounce string measure of mass in the US system
  • Pound string measure of mass in the US system
  • Stone string measure of mass in old British terminology
  • ImperialTon string a ton as defined by British Imperial units
  • USTon string a ton as defined in the US
  • grain string measure of mass in old Greek system terminology
  • dram string measure of mass in old Greek system terminology
  • TroyOunce string measure of mass in old Greek system terminology
  • TroyPound string measure of mass in old Greek system terminology
  • Pennyweight string measure of mass in old Greek and British terminology
  • Kilopascal 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 milliLiter
  • Pinch 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 Classabbr.name/desc
CountUnit types Count: to indicate or name by units or groups so as to find the total number of units involved
countname for all item types
eaEach (item)
eachEach (item)
levelmay identify a count for a level or rank
percentagemay identify a count in a percentage ratio
percentagemay identify a count in a percentage ratio
percentmay identify a count in a percentage ratio
pctmay identify a count in a percentage ratio
%may identify a count in a percentage ratio
LightMeasurement 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)
luxMeasure of light intensity
AmpereMeasurement of electrical current: An international System of units (SI) term.
ampmeaning 1 ampere
milliampere1/1000 of an ampere
milliamp1/1000 of an amp
milliampsoptional plural of same
maAbbreviation for milliamp
VoltMeasurement of electrical potential when measured at 1 ampere with a resistance of 1 ohm
voltageVolt
voltVolt
voltsoptional plural of same
vAbbreviation of volt
kilovolt1000 volts
kvAbbreviation of kilovolt
millivolt1/1000 volts
mvAbbreviation of millivolt
mvoltAbbreviation of millivolt
PowerMeasurement of Power: a source or means of supplying energy
horsepowerDefined originally as the power of a pulling horse.
hpAbbreviation of horsepower
wattpower produced by a current of one ampere across a potential difference of one volt
wAbbreviation of watt
milliwatt1/1000 watt
kilowatt1000 watts
mwAbbreviation of milliwatt
kwAbbreviation of kilowatt
AngleMeasure of separation of two vectors; the amount of turning necessary to bring one line or plane into coincidence with or parallel to another
degreeTerm of measurement of an angle where 360 degrees comprise a full rotation.
radianTerm 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
radiansoptional plural of same
angleUsed as a synonym for 'degree'
angular degreesUsed as a synonym for 'degree'
angulardegreesUsed as a synonym for 'degree' (for certain coding purposes)
degAbbreviation for 'degree'
radAbbreviation for 'radian'
TimeMeasurements of duration or interval
timebase type for time is the 'second'
seconda unit of time we are all familiar with
secondsoptional plural of same
microsecondone millionth of a second
millisecondone thousandth of a second
usAbbreviation for microsecond (derived from µs, substituting ASCII 'u' for 'µ')
msAbbreviation for millisecond
secAbbreviation for Second
minutea unit of time we are all familiar with. Equal to 60 seconds
minutesoptional plural of same
minAbbreviation for Minute
houra unit of time we are all familiar with. Equal to 60 minutes
hoursoptional plural of same
hrAbbreviation of hour
daya unit of time we are all familiar with. Equal to 24 hours
daysoptional plural of same
dyAbbreviation of day
montha unit of time we are all familiar with. Equal to 1/12 Year. Note: not all months are equivalent. This is a generalized average.
monthsoptional plural of same
moAbbreviation of month
yeara 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.
yearsoptional plural of same
yrAbbreviation of year
TenperatureMeasurement of the warmth or coldness of an object or substance with reference to some standard value.
degrees celsiusmetric and SI standard for temperature measurement worldwide.
celsiusSynonym for 'degrees celsius'
degreescelsiusSynonym for 'degrees celsius' (for certain coding purposes)
degrees cSynonym for 'degrees celsius'
celsiusSynonym for 'degrees celsius'
centigrade*degrees celsiusmetric and SI standard for temperature measurement worldwide.
fahrenheitsyonymous with degrees fahrenheit
degrees fahrenheitimperial system of measurement still standard in the US and its territories.
degrees fsyonymous with degrees fahrenheit
fAbbreviation for degrees fahrenheit
kelvinKelvin 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.
klvAbbreviation for Kelvin
LengthMeasurement of size and local distance. Overlaps "Distance" in terms of scale. Prefer Length for sub-kilometer measures.
lengthbase unit of Length is the Meter
meterThe SI and metric standard used for measurement (except US)
metersoptional plural of same
mAbbreviation for meter
decimeter1/10th of a meter
decimetersoptional plural of same
dmAbbreviation for decimeter
centimeter1/100th of a meter
centimetersoptional plural of same
cmAbbreviation for centimeter
millimeter1/1000th of a meter
millimetersoptional plural of same
mmAbbreviation for millimeter
micometerone millionth of a meter
micometersoptional plural of same
umAbbreviation for micometer
hectometer100 meters
hectometersoptional plural of same
hmAbbreviation for hectometer
inchUS Inch
inchesoptional plural of same
footUS Foot. Equivalent to a dozen (12) inches.
feetoptional plural of same
ftAbbreviation for foot
yardUS yard. Equivalent to 3 feet.
yardsoptional plural of same
ydAbbreviation for yard
DistanceMeasurement of distances. Overlaps Length in terms of scale. Prefer Distance for Kilometer and above.
distancebase type for distance is the kilometer.
kilometerMetric and SI standard for distance measurement
kilometersoptional plural of same
kmAbbreviation for kilometer
100kmOne hundred Kilometers
one humdred kilometersSynonym for 100km
onehumdredkilometersSynonym for 100km
100 kilometersSynonym for 100km
onehumdredkmSynonym for 100km
100 kmSynonym for 100km
mileUS Mile measurement for distance (about 2.2 kilometers)
milesoptional plural of same
miAbbreviation for mile
VolumeMeasure of occupied space
volumeThe base type for Volume is the Liter
literThe metric and SI standard for volume measurement
litersoptional plural of same
lAbbreviation for liter
microliterone millionth of a liter
microlitersoptional plural of same
ulAbbreviation for microliter (derived from µl, substituting ASCII 'u' for 'µ')
milliliter1/1000th liter
millilitersoptional plural of same
cubic centimeterequivalent to milliliter
cm3Abbreviation for cubic centimeter
ccAbbreviation for cubic centimeter
mlAbbreviation for milliliter
centiliter1/100th liter
centilitersoptional plural of same
clAbbreviation of centiliter
deciliterone tenth liter
decilitersoptional plural of same
dlAbbreviation for deciliter
fluid ounceUS Unit of measure
fluid ouncesoptional plural of same
fluidouncesynonym for FLuid ounce (for certain coding purposes)
fl ounceAbbreviation for Fluid Ounce
fl. ounceAbbreviation for Fluid Ounce
fl. ouncesoptional plural of same
fl ozAbbreviation for Fluid Ounce
flozAbbreviation for Fluid Ounce
fl. ozAbbreviation for Fluid Ounce
fl. ounceAbbreviation for Fluid Ounce
fl.ozAbbreviation for Fluid Ounce
pintUS Unit of measure
pintsoptional plural of same
ptAbbreviation for Pint
quartUS Unit of measure
quartsoptional plural of same
qtAbbreviation for quqrt
gallonUS Unit of measure
gallonsoptional plural of same
galAbbreviation of gallon
teaspoonUS kitchen measure unit
tspAbbreviation for teaspoon
tAbbreviation for teaspoon
tablespoonUS kitchen measure unit
tbspAbbreviation for tablespoon
tbAbbreviation for tablespoon
cupUS kitchen measure unit
cAbbreviaion for cup
dropColloquial measurement
dripsynonym for drop
drpAbbreviation for drop
pinchColloquial measurement
pchAbbreviation for pinch
dashColloquial measurementa
dshAbbreviation for dash
cubic meterCubic meter
cubicmeterSynonym fro cubic meter
m3Abbreviation for cubic meter
cubic centimeterCubic centimeter (see also milliliter)
cubiccentimeterSynonym for cubic centimeter
cubic footUS cubic foot
cubicfootSynonym for cubic foot
ft3Abbreviation for cubic feet
cftAbbreviation for cubic feet
cfAbbreviation for cubic feet
cubic inchUS cubic inch
cubicinchSynonym for cubic inch
ciAbbreviation for cubic inch
cinAbbreviation for cubic inch
MassMass 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.
massthe base unit for mass measurement is the gram
gramthe metric and SI standard for mass measurement.
gAbbreviation for gram
microgramone millionth of a gram
mcgAbbreviation of microgram
ugAbbreviation of microgram (derived from µg, substituting ASCII 'u' for 'µ')
milligram1/1000th of a gram
mgAbbreviation of milligram
kilogram1000 grams
kgAbbreviation of kilogram
ounceUS measure of weight. 1/16 Pound
ouncesoptional plural form of same
ozAbbreviation of ounce
ozsoptional plural form of same
poundUS Standard weight measure
poundsoptional plural form of same
lbAbbreviation for pound
lbsoptional plural form of same
stonearchaic imperial measure
stAbbreviaiton for stone
metric tonmetric and SI definition of a 'ton'
metrictonsynonym for metric ton
tonnesynonym for metric ton
mtonAbbreviation for metric ton
mtAbbreviation for metric ton
imperial tonBritish Imperial definitio of 'ton'
imperialtonsynonym for imperial ton
itonAbbreviation for imperial ton
long tonsynonym for Imperial ton
longtonsynonym for long ton
l. tonAbbreviation for long ton
l.tonAbbreviation for long ton
l. tnAbbreviation for long ton
l.tnAbbreviation for long ton
ltnAbbreviation for long ton
us tonUS definition for 'ton'
ustonsynonym for US Ton
short tonsynonym for US Ton
shorttonsynonym for Short Ton
sh, tonsynonym for Short Ton
sh.tonsynonym for Short Ton
sh. tnsynonym for Short Ton
sh.tnsynonym for Short Ton
shtnsynonym for Short Ton
grainArchaic measurement of small masses (Greek / British)
grAbbreviation for grain
dramArchaic measurement of small masses (Greek / British)
drAbbreviation for dram
troy ounceArchaic weight measurement (Greek / British)
troyouncesynonym for troy ounce
oz tAbbreviation for troy ounce
oztAbbreviation for troy ounce
troy poundArchaic weight measurement (Greek / British)
troypoundsynonym for troy pound
lb tAbbreviation for troy pound
lbtAbbreviation for troy pound
pennyweightArchaic weight measurement (Greek / British)
dwtAbbreviation for pennyweight
pwtAbbreviation for pennyweight
pwAbbreviation for pennyweight
PressurePressure is defined as the physical force exerted on an object.
pressureThe base unit of pressure is the kilopascal (Kpa)
kilopascalThe SI standard for pressure measurement.
kpaAbbreviation for kilopascal
megapascal1000 Kpa
mpaAbbreviation for megapascal
pounds per square inchUS unit measure if si many pounds per square inch of surface area
poundspersquqreinchsynonyn for pounds per square inch
poundspersqinAbbreviation for pounds per square inch
psiAbbreviation for pounds per square inch
lb/in2Abbreviation for pounds per square inch
kg per square centimeterPressure of so many kilograms per square centimeter of surface area
kgpersquarecentimeterSynonym for kg per square centimeter
kgpersqcentimeterSynonym for kg per square centimeter
kg/cm2Abbreviation for kg per square centimeter
TorqueTorque 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.
torqueThe Newton Meter is the SI standard unit of torque
newton meterThe Newton Meter is the SI standard unit of torque\
newtonmeterSynonymous with newton meter
nmAbbreviation of Newton Meter
gram force centimeterAlternative measure of torque
gram-force centimeterSynonym to gram force centimeter
gram force cmSynonym to gram force centimeter
gram-force cmSynonym to gram force centimeter
gfcmAbbreviation for gram force centimeter
gf*cmAbbreviation for gram force centimeter
foot poundUS measure of torque
footpoundSynonym to foot pound
ft lbsAbbreviation for foot pound
lbftAbbreviation for foot pound
pound-force footSynonym 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.resolveSynonym(abbrevIn)
 // 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 set
  • unitIn {string} The unit to match to a canonical UnitType and set value as
  • value {number} The value to set
Examples
let myMeasure = new Length()
 NameMapUnit.setMeasureAs(myMeasure, 'feet', 6.4)
getMeasureAs

Returns the value of the provided Measure in units expressed by the resolved synonym

Parameters
  • measure {Measure} The Measure object to read
  • unitIn {string} The unit to match to a canonical UnitType for value
Examples
:
 let myMeasure = new Length(UnitType.Inch, 27)
 let feet = NameMapUnit.getMeasureAs(myMeasure, 'feet')

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 UnitType
  • measure2Type UnitType

Returns number

NameMapRatio

Lookup table for common measurements and their associated compositions

Basic Ratios
common abbr.full nameinstance typenumerator unitdenominator unit
ratiogeneric ratioRatioUnitType.CountUnitType.Count
deg/secdegrees per secondRatioUnitType.DegreeUnitType.Second
rpmrevolutions per minuteRatioUnitType.CountUnitType.Minute
Densities
common abbr.full nameinstance typenumerator unitdenominator unit
g/ccgrams per cubic centimeterDensityUnitType.GramUnitType.Milliliter
g/mlgrams per milliliterDensity, UnitType.GramUnitType.Milliliter
kg/lkilograms per literDensity, UnitType.KilogramUnitType.Liter
oz/fl.ozounces per fluid ounceDensityUnitType.OunceUnitType.FluidOunce
lb/galpounds per gallonDensity, UnitType.PoundUnitType.Gallon]
g/tspgrams per teaspoonDensity, UnitType.GramUnitType.Teaspoon
g/tbspgrams per tablespoonDensityUnitType.GramUnitType.Tablespoon
speeds
common abbr.full nameinstance typenumerator unitdenominator unit
mphmiles per hourSpeedUnitType.MileUnitType.Hour
kphkilometers per hourSpeedUnitType.KilometerUnitType.Hour
mpsmeters per secondSpeedUnitType.MeterUnitType.Second
fpsfeet per secondSpeedUnitType.FootUnitType.Second
Fuel Efficiencies
common abbr.full nameinstance typenumerator unitdenominator unit
mpgmiles per gallonFuelEfficiencyUnitType.MileUnitType.Gallon
kpgkilometers per gallonFuelEfficiencyUnitType.KilometerUnitType.Gallon
kplkilometers per literFuelEfficiencyUnitType.KilometerUnitType.Liter
mplmeters per literFuelEfficiencyUnitType.MeterUnitType.Liter
l/100kmliters per 100kmFuelEfficiencyUnitType.OneHundredKmUnitType.Liter
Accelerations
common abbr.full nameinstance typenumerator unitdenominator unit
m/s2meters per second squaredAccelerationUnitType.MeterUnitType.Second
mps/secmeters per second squaredAccelerationUnitType.MeterUnitType.Second
ft/s2feet per second squaredAccelerationUnitType.FootUnitType.Second
fps/secfeet per second squaredAccelerationUnitType.FootUnitType.Second

makeFrom

Creates an appropriate compound Measure Ratio object for the given name and values

Parameters
  • ratioName string Name of the ratio to match to
  • value1 number Value of the ratio, or the value of the numerator
  • value2 number Value of the denominator or undefined - to avoid a dangerous division by zero (optional, default 1)
Examples
let mySpeed = NameMapRatio.makeFrom('mph', 60, 1)
 let myMPG = NameMapRatio.makeFrom('mpg', 400, 14.5)
 mySpeed.getValue() // 60
 myMPG.getValue() // 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 0
  • timeValue 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 set
  • ratioType 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
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Angle

Defines measure for Angles. UnitType Degree is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

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, default 0)
  • volumeValue number The value for time (default 1) (optional, default 1)

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
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

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 1
  • volumeValue 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
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Light

Defines measure for light intensity. UnitType Lux is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Mass

Defines measure for mass. UnitType Gram is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Power

Defines measure for Power. UnitType Watt is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Pressure

Defines measure for Pressure. UnitType Kilopascal is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

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, default 0)
  • timeValue number The value for time (default 1) (optional, default 1)
getKilometersPerHour

Returns this Speed value in kilometers per hour

Returns number

setKilometersPerHour

Sets this Speed value in Kilometers per hour

Parameters
getMilesPerHour

Returns this Speed value in miles per hour

Returns number

setMilesPerHour

Sets this Speed value in Miles per hour

Parameters

Temperature

Defines measure for Temperature. UnitType Celsius is the base unit.

Contains functions for common conversions.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Time

Defines measure for Time. UnitType Second is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Torque

Defines measure for Torque. UnitType NewtonMeter is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Voltage

Defines measure for Electric Voltage. UnitType Volt is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

Volume

Defines measure for Volume. UnitType Liter is the base unit.

Constructor
Parameters
  • value number? The value.
  • valueUnitType string? The UnitType of the initializing value

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

Keywords

unit

FAQs

Package last updated on 15 Nov 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts