0.1.2 • Published 3 years ago

unit-measure v0.1.2

Weekly downloads
2
License
MIT
Repository
github
Last release
3 years ago

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 'µ')