ArrayCollection for AS2
Did you know that AS2 includes rudimentary implementations of collections and iterators? I didn't until a few months back, but they do come in handy from time to time. An added bonus is that they make me less sad about developing in AS2 and missing out on all that AS3 goodness when the project requires FP8 compatibility.
Anyhow, the default implementation still leaves a bit to be desired, especially for those of us who spend the majority of our time coding AS3. The built-in class not only bears the unfortunate name CollectionImpl (which implements the Collection interface, both of which reside in the mx.utils package), but it also lacks some methods I've grown to appreciate in AS3's ArrayCollection class. Those methods are as follows:
- length (getter)
- addItemAt()
- contains()
- getItemIndex()
- removeAll()
- removeItemAt()
The following class provides those methods. I know, nothing fancy or impressive, but useful (in my opinion) nonetheless. CollectionImpl isn't all bad though, it does provide us with most of the basic collection-related functionality you would expect, including the removeItem() method that was left off of AS3's ArrayCollection class. As such, this class inherits from CollectionImpl and attempts to fill in the blanks.
import mx.utils.CollectionImpl;
class com.returnundefined.utils.ArrayCollection extends CollectionImpl implements Collection
{
private var _items:Array;
public function ArrayCollection(arr:Array)
{
super();
_items = (arr == null) ? new Array() : arr;
}
public function get length():Number
{
return _items.length;
}
public function addItemAt(item:Object, index:Number):Boolean
{
var result:Boolean = false;
if(item != null)
{
_items.splice(index, 0, item);
result = true;
}
return result;
}
public function contains(item:Object):Boolean
{
return getItemIndex> -1;
}
public function getItemIndex(item:Object):Number
{
var index:Number = -1;
var len:Number = length;
for(var i:Number = 0; i <len; i++)
{
if (_items[i] == item)
{
index = i;
break;
}
}
return index;
}
public function removeAll():Void
{
_items = new Array();
}
public function removeItemAt(index:Number):Boolean
{
return removeItem(getItemAt(index));
}
}
Feel free to alter the package path here and insert this class into your library wherever you want.

