ModulusModulus

This were taken from a post of gskinner.com.

Using Modulus for Alternation
This is perhaps the simplest use case. Say you want to alternate row colors in a list – you can simply make the color of each row a function of the modulus value of the rowcount:

if (rowIndex % 2 == 0) 
{
   rowColor = 0xFFFFFF;
} 
else
{
   rowColor = 0xCCCCCC;
}

Using Modulus to Vary Frequency
Similar to the above, you can use modulus to vary the frequency of execution of a block of code within a repeating block. For example:

// tick runs every frame:
function tick() {
   trace("I run every frame");
   if (++frameCount % 10 == 0) {
      trace("I run every 10 frames");
    }
}

Using Modulus to Wrap Values
You can also modulus to wrap a value within a specified range. For example, if you want to a sprite to move right, but wrap back to the left side of the screen when it hits the right side, you could use this:

sprite.x = (sprite.x + 5) % stage.stageWidth;

It’s easy to modify this to work with negative x motion as well, you simply have to ensure the value is always positive:

sprite.x = (sprite.x + velX + stage. stageWidth) % stage. stageWidth;

Using Modulus to Flatten Two Dimensional Data Sets
Creating two dimensional arrays by nesting arrays is very inefficient. It’s much better to flatten the 2D data into a single array. You can do this easily using modulus and simple multiplication:

// iterate the array:
function scanArray() {
   for (var i=0; i < flatArray.length; i++) {
      var x = i%columns;
      var y = Math.floor(i/columns);
      trace("value at x="+x+",y="+y+" is '"+flatArray[i]+"'");
    }
}
 
// access individual values:
function getValueAt(x,y) {
   return flatArray[x+y*columns];
}