Looping within a range


Something I have to do very often is looping a number within a range. This could be for a carousel navigation, a rotating banner or image slideshow, etc. The concept is simple, have a range, say 1 – 20, and simply call next() / previous() on it and return the new number, if it goes above 20, return to 1, if below 1, return to 20.

The AS2.0 class is as follows
[as]
class com.pixelbreaker.number.LoopRange
{
public var min:Number;
public var max:Number;

private var _current:Number;

function LoopRange( min:Number, max:Number, start:Number )
{
this.min = min;
this.max = max;
_current = start || min;
}

public function next():Number
{
_current = _current+1 <= max? _current+1 : min;
return _current;
}

public function previous():Number
{
_current = _current-1 >= min? _current-1 : max;
return _current;
}

public function set current( value:Number ):Void
{
if( value >= min && value <= max ) _current = value;
else throw new GenericError( ‘number ‘ + value + ‘ is out of range [ ' + min + ', ' + max + ' ]‘ );
}

public function get current():Number
{
return _current;
}
}
[/as]

To implement this on an array you would do the following

[as]
import com.pixelbreaker.number.LoopRange;

var slideShowImages:Array = [];
for( var i:Number = 0; i {
slideShowImages.push( xmlNode.childNodes[ i ].attributes.src );
}

var loopRange:LoopRange = new LoopRange( 0, slideShowImages.length-1 );

// to load the next image:
myMovieClip.loadMovie( slideShowImages[ loopRange.next() ] );

[/as]

I’ll add the AS3 class soon, it’s barely any different

Comments are closed.