npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

unit-measure

v0.1.2

Published

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

Downloads

2

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.

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

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