Useful JavaScript Game Extensions: Number#round

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.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: