Skip to content

Instantly share code, notes, and snippets.

@jfridye
Created June 30, 2015 22:39
Show Gist options
  • Save jfridye/5e97ec49b601ec271de7 to your computer and use it in GitHub Desktop.
Save jfridye/5e97ec49b601ec271de7 to your computer and use it in GitHub Desktop.
/**
* Handles converting a magnitude from one unit to another.
* @module convert
*/
const CONVERSION_TABLE = {
m: { ft: 3.2808 }, // elevation
km: { mi: .62137 }, // distance
kcal: { kj: 4.1868 }, // energy
kph: { mph: .62137 }, // speed
kg: { lb: 2.2046 }, // weight
'min/km': { 'min/mi': 1.60934 } // pace
};
/**
* Creates a new conversion object, but not intened to be used with the `new`
* keyword. Not intended to be used by itself, but instead to chain additional
* methods.
* @param {number} magnitude - the initial value of the magnitude
* @return {object} the `convert` instance
*/
function convert (magnitude) {
this.initialMagnitude = magnitude;
return this;
};
/**
* Specify the unit of the magnitude parameter passed to `convert()`. Only
* intended to be used when chained to `convert()`.
* example: convert(1).from('mi')
* @param {string} unit - describes the unit, like `mi` or `km`
* @return {object} - the convert instance
*/
convert.prototype.from = function (unit) {
this.rawInitialUnit = unit;
this.initialUnit = this.rawInitialUnit.toLowerCase();
return this;
};
/**
* Specify the unit to which to convert the magnitude. Only intended to be used
* when chained to `from()`.
* example: convert(1).from('mi').to('km')
* @param {string} unit - describes the ouput unit after conversion
* @return {number} - the resulting magnitude from the conversion
*/
convert.prototype.to = function (unit) {
let multiplier;
this.rawResultUnit = unit;
this.resultUnit = this.rawResultUnit.toLowerCase();
if (this.initialUnit === this.resultUnit) {
multiplier = 1;
} else if (this.initialUnit in CONVERSION_TABLE) {
multiplier = CONVERSION_TABLE[this.initialUnit][this.resultUnit];
} else if (this.resultUnit in CONVERSION_TABLE) {
multiplier = 1 / CONVERSION_TABLE[this.resultUnit.][this.initialUnit];
}
return this.initialMagnitude * multiplier;
};
export default new convert();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment