Skip to content

Instantly share code, notes, and snippets.

@lyquix-owner
Created April 23, 2020 20:15
Show Gist options
  • Save lyquix-owner/b6702a63817214ade53d3ea730cc2731 to your computer and use it in GitHub Desktop.
Save lyquix-owner/b6702a63817214ade53d3ea730cc2731 to your computer and use it in GitHub Desktop.
Javascript function to convert length, weight, area, and volume units with ease
/**
* unitConv - converts length, weight, area and volume units
*
* Usage: unitConv.type(value, unitIn, unitOut)
* type: length | weight | area | volume
* v: numeric value
* unitIn: name of the input unit
* unitOut: name of the output unit
*
* Supported units:
* length: mm, cm, m, km, in, ft, yd, mi, nm
* weight: g, kg, lb, oz, ct (carat), st (short ton), lt (long ton), ton, gr (grains)
* area: cm2, m2, ha, km2, in2, ft2, yd2, mi2, ac (acre)
* volume: ml, l, m3, in3, ft3, pt (pint), qt (quart), gal, bbl (barrel)
*
*/
var unitConv = (function(){
var r = {};
['length', 'weight', 'area', 'volume'].forEach(function(type){
r[type] = function(value, unitIn, unitOut) {
return this.conv(type, value, unitIn, unitOut);
};
})
r.conv = function(type, value, unitIn, unitOut) {
// List of factors
let factors = {
length: {mm: 1000, cm: 100, m:1, km: 0.001, in: 39.370078740157, ft: 3.2808398950131, yd: 1.0936132983377, mi: 0.00062137119223733, nm: 0.00053995680345572},
weight: {g: 1000, kg: 1, lb: 2.2046226218488, oz: 35.27396194958, ct: 5000, st: 0.0011023113109244, lt: 0.00098420652761106, ton: 0.001, gr: 15432.358352941},
area: {cm2: 10000, m2: 1, ha: 0.0001, km2: 0.000001, in2: 1550.0031000062, ft2: 10.76391041671, yd2: 1.1959900463011, mi2: 0.00000038610215854781, ac: 0.00024710538146717},
volume: {ml: 1000, l: 1, m3: 0.001, in3: 61.023744094732, ft3: 0.035314666721489, pt: 2.1133764188652, qt: 1.0566882094326, gal: 0.26417205235815, bbl: 0.0083864143605761}
};
// unitIn to base then base to unitOut
return (value / factors[type][unitIn]) * factors[type][unitOut];
}
return r;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment