Useful JavaScript Game Extensions Part 8, Number#mod

Part 8/258 Number#mod

For some bizarre reason, JavaScript does not constrain the result of the % operator to be between 0 and the base. This can make computing the index into an array or “wrapping” a negative number a small pain. This method gives all numbers an improved mod method that will guarantee they end up inside the array.

/**
 * A mod method useful for array wrapping. The range of the function is
 * constrained to remain in bounds of array indices.
 *
 * Example:
 * (-1).mod(5) === 4
 *
 * @param {Number} base
 * @returns An integer between 0 and (base - 1) if base is positive.
 * @type Number
 */
Number.prototype.mod = function(base) {
  var result = this % base;

  if(result  0) {
    result += base;
  }

  return result;
};

This makes jumping into an index much easier.

// Example usage
var result = array[n.mod(array.length)];

Though still not quite as nice as in Ruby where you can do:

result = array[n] # Ruby cares enough to make it happen

I love Ruby…

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s