11 December 2007

Array.shuffle() in AS3

Here's an AS3 class called ExtendedArray that unsurprisingly extends the functionality of the Array class. One important thing to note is that it is a dynamic class. This allows you to add properties and methods to the base class at runtime.

Another thing to note is looping through the optionalArgs (or "rest" arguments as they're known) and using super.push() to populate the Array in the constructor. Simply using super(optionalArgs) would create an array within the Array i.e. a 2d array.

The shuffle function is just a slightly different version of the AS2 shuffle functions you can find on the web. Using the asterisk (*) as a datatype means that any type can be handled by the shuffle function.


package com.utils
{
dynamic public class ExtendedArray extends Array
{
public function ExtendedArray(... optionalArgs){
for each (var value:* in optionalArgs){
super.push(value);
}
}

public function shuffle(startIndex:int = 0, endIndex:int = 0):Array{
if(endIndex == 0) endIndex = this.length-1;
for (var i:int = endIndex; i>startIndex; i--) {
var randomNumber:int = Math.floor(Math.random()*endIndex)+startIndex;
var tmp:* = this[i];
this[i] = this[randomNumber];
this[randomNumber] = tmp;
}
return this;
}
}
}

You could add many more functions to this to increase the functionality of the base Array class.