MCO, handle your measurements properly!

February 19, 2012    imperial system javascript metric system unit unit value value

For future use, I have developed MCO (NPM), a unit value library written in JavaScript. MCO stands for Mars Climate Orbiter, a robotic space probe launched by NASA. The name was chosen because the MCO itself exploded due to a calculation error where imperial units were mixed with metric system units.

MCO tries to prevent calculation errors by keeping track of the unit for each value. It checks whether you are accidentally trying to mix different units. Also, it allows one to perform calculations with unit values. The source below shows how to use the library:

var mco = require('./');
var MetricSystem = mco.MetricSystem;

// trying to add two values with different types
try {
    var m = new mco.UnitValue(5, MetricSystem.METRE);
    var ft = new mco.UnitValue(10, new mco.BaseUnit(mco.Quantity.LENGTH, 'ft'));
    m.add(ft);
} catch (err) {
    console.log('cannot add ft to m');
}

// homework: Sally is riding her bicycle with a speec of 5 [m/s]. What distance has she traveled after 15 minutes?
var sallySpeed = new mco.UnitValue(5, MetricSystem.METRES_PER_SECOND);
var sallyTimeMinutes = new mco.UnitValue(15, new mco.BaseUnit(mco.Quantity.TIME, 'min'));
var sallyTimeSeconds = mco.UnitTransformer.transform(sallyTimeMinutes, MetricSystem.SECOND);
var sallyDistance = sallySpeed.multiply(sallyTimeSeconds);

console.log('Sally\'s speed', sallySpeed.toString());
console.log('Sally\'s time in minutes', sallyTimeMinutes.toString());
console.log('Sally\'s time in seconds', sallyTimeSeconds.toString());
console.log('Sally\'s distance', sallyDistance.toString());

// homework: Hank is accelerating with 10 m/s^2. How fast is he going after 25 seconds?
var hankAcceleration = new mco.UnitValue(10, MetricSystem.METRES_PER_SQUARE_SECOND);
var hankTime = new mco.UnitValue(25, MetricSystem.SECOND);
var hankSpeed = hankAcceleration.multiply(hankTime);
console.log('Hank\'s acceleration', hankAcceleration.toString());
console.log('Hank\'s time', hankTime.toString());
console.log('Hank\'s speed', hankSpeed.getSimplified().toString());

And the resulting output:

cannot add ft to m
Sally's speed 5 [m/s]
Sally's time in minutes 15 [min]
Sally's time in seconds 900 [s]
Sally's distance 4500 [m]
Hank's acceleration 10 [m/s/s]
Hank's time 25 [s]
Hank's speed 250 [m/s]

To use the library in a browser, Browserify can be used.

MCO is released under the 2-clause BSD license.



comments powered by Disqus