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…