A node JS measurement utility to convert, manipulate and format units.
TODO
var measure = require('measure');
var weight = measure('4kg');
weight.config(path/to/measurement/weights.json);
Converting units to other types uses the to
method
weight.config(path/to/measurement/weights.json);
...
var weight = measure('4kg');
// --> all these do the same thing!
weight.to('pounds');
weight.to('p');
// --> you can also chain convertions, but you shouldn't need too
weight.to('pounds').to('kg').to('tons').to('grams').......
- Adding units uses the
add
method - Subtracting units uses the
sub
method
you can add/subtract any type as long as it has a common base type
weight = measure('5kg');
weight.add('5p').add('5 kilograms').sub('3g').sub('6kg');
weight.add(5); //--> adds 5 of the current type, in this case 'kg'
returns a measurement object that takes the initial condition as the type. The above example will return a value in kg since weight = measure('5kg')
is initialised to 'kg'. If you require the unit to be converted after the addtion just chain it like so
weight.add('5p').add('5 kilograms').add('3g').sub('6kg').to('tons');
- Multiplying units uses the
times
method - Dividing units uses the
by
method
Multiplication and division operators are different in the sense that if the unit type is different between them they can produce a new unit type.
for example
var distance = measure('5m');
var speed = distance.by('s'); // --> returns a m/s unit type
var speed = distance.by(time); // --> returns a m/s unit type
var area = distance.times(distance); // --> returns m^2 unit type
var volume = distance.times(distance).times('3m'); // --> returns m^3 unit type;
combining these two allow us to perform more actions on more complex unit types
area.by(speed) // -> returns m^2/s
you can now couple this with the to
method to perform some interesting conversions
speed.to('km/hr');
speed.to('km/day');
speed.to('years/km'); // --> measure js will notice a flip in units and handle an inversion
Some systems may rely on custom units to intergrate seamlessly. To do this you need to provide a configuration JSON file/object
For an example we are going to create the time
unit. note: the time unit has already been provided so it does not need to be implemented.
- Create a configuration file
- Associate it with the unit you want to manipulate
{
[
{
unit: 's',
multiplier: 1,
name: 'second',
plural: 'seconds'
},
{
unit: 'min',
multiplier: 0.0166666666, // 1/60
name: 'minute',
plural: 'minutes'
},
{
unit: 'hr',
multiplier: 0.000277777777, // (1/60)/60
name: 'hour',
plural: 'hours'
},
{
unit: 'ms',
multiplier: 100
name: 'millisecond',
plural: 'milliseconds'
},
]
}
now you are ready to use the time.json
you just created!
var time = measure('5s').config('path\to\time.json');