Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created March 25, 2014 14:38
Show Gist options
  • Save jarrettmeyer/9763151 to your computer and use it in GitHub Desktop.
Save jarrettmeyer/9763151 to your computer and use it in GitHub Desktop.
An idea for unit conversions in javascript
var ConversionStrategy = (function () {
function ConversionStrategy() {
}
ConversionStrategy.prototype.valueOf = function (value) {
return -1;
};
return ConversionStrategy;
})();
var PeopleConversionStrategy = (function () {
function PeopleConversionStrategy() {
this.units = "people";
}
PeopleConversionStrategy.prototype.valueOf = function (value) {
if (value > 100000000) { // 100,000,000 => "0.1 B"
return (value / 1000000000).toFixed(1) + " B";
} else if (value > 100000) { // 100,000 =? "0.1 M"
return (value / 1000000).toFixed(1) + " M";
}
return value;
};
return PeopleConversionStrategy;
})();
var TonsConversionStrategy = (function () {
function PeopleConversionStrategy() {
this.units = "tons";
}
TonsConversionStrategy.prototype.valueOf = function (value) {
if (value > 100000) { // 100,000 => "0.5 kton"
return (value / 2000000).toFixed(1) + " kton";
} else if (value > 1000) { // 1,000 => "0.5 ton"
return (value / 2000).toFixed(1) + " ton";
} else {
return value.toFixed(0) + " lbs";
}
};
return TonsConversionStrategy;
})();
var UnitConverter = (function () {
var strategies = {
"people": PeopleConversionStrategy,
"tons": TonsConversionStrategy,
"*": DefaultConverstionStrategy
}
function UnitConverter() {
}
UnitConverter.prototype.units = function (units) {
return strategies[units];
};
return UnitConverter;
})();
var convert = new UnitConverter();
// usage:
// convert.units("people").valueOf(7200000000) => "7.2 B"
// convert.units("tons").valueOf(5200000) => "2.6 kton"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment