Scripting: handling units of length
How do you all handle using different units in your scripts?
Where I'm from we mostly use millimetres for measuring, but I know a lot of you use inches, and of course most of the built-in methods use points.
Here's some ways I've used to deal with different units:
(a) make a conversion function
// preparation:
var inches = function (n) { return n * 72 };
var mm = function (n) { return n * 72 / 25.4 };
// usage:
needsValueInPoints(inches(2));
needsValueInPoints(mm(60));
// just for testing:
function needsValueInPoints(lengthInPts) {
alert(lengthInPts + ' points!');
}
(b) overload Number.prototype with the conversion methods
// preparation:
Number.prototype.inches = function () { return this * 72 };
Number.prototype.mm = function () { return this * 72 / 25.4 };
// usage:
needsValueInPoints((2).inches());
needsValueInPoints((60).mm());
// note: must surround literal number with parenthesis or dot notation will look like decimal point! Awkward!
// just for testing:
function needsValueInPoints(lengthInPts) {
alert(lengthInPts + ' points!');
}
(c) make a converting wrapper function
// preparation:
function needsValueInInches(lengthInInches) {
needsValueInPoints(lengthInInches * 72);
}
function needsValueInMM(lengthInMM) {
needsValueInPoints(lengthInMM * 72 / 25.4);
}
// usage:
needsValueInInches(2);
needsValueInMM(60);
// just for testing:
function needsValueInPoints(lengthInPts) {
alert(lengthInPts + ' points!');
}
Any better ways?
