It is beyond anything you have ever experienced or imagined
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 && base > 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…
| Print article | This entry was posted by Daniel X Moore on September 9, 2010 at 8:12 pm, and is filed under 256 JavaScript Game Extensions, Game Development, Programming. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

