Part 13
Here’s another small one, in the same vein as yesterday’s. When you can take for granted that numbers behave as objects, it really cleans up unnecessary references to static Math
methods and extra helper methods.
/** * @returns The number rounded to the nearest integer. * * (4.5).round(); // => 5 * (4.4).round(); // => 4 */ Number.prototype.round = function() { return Math.round(this); };
Take a look back at the original useful JavaScript game extension Number#Clamp
. Though global helper functions have the same number of semantic elements, I find that it’s easier to break down in my head if they are attached to objects. Also, the order of the parameters may be more obvious if you reduce it from 3 to 2.