Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

May 8, 2014

Return to the beginning of an array with a ternary operator

Often times when iterating and looping over the contents of an array, I want to set the current index to zero if it's reached the last element. Generally this happens in the form of an if/else statement, but I enjoy using a more terse form with the help of a ternary operator. See the code below, and enjoy!
var myArray = ['one', 'two', 'three', 'four'];
var curIndex = 0;

setInterval(function(){
    console.log(myArray[curIndex]);
    curIndex = (curIndex < myArray.length - 1) ? curIndex + 1 : 0;
}, 500);

April 23, 2012

Processing: Flip a PImage horizontally

I needed a mirror image of a PImage in my Processing project, so I came up with this little snippet:
public PImage getReversePImage( PImage image ) {
 PImage reverse = new PImage( image.width, image.height );
 for( int i=0; i < image.width; i++ ){
  for(int j=0; j < image.height; j++){
   reverse.set( image.width - 1 - i, j, image.get(i, j) );
  }
 }
 return reverse;
}