views:

1914

answers:

4

I just finished writing my own collecion class, and i'd really like to make it iterable with the for each or the simple for construct, or just to access elements with the collection[key] notation.

I've written a getElementAt(index):MyOwnElement function, but using it, is not as sexy as using the square brachets, don't even let me start on iterating..

Is there any way?

+1  A: 

There's a pretty good article on implementing the iterator pattern in AS3 here

Polygraf
A: 

You can not override operator in AS3.
I think you may change 'getElementAt' to a short name likes 'at':) or assgin getElementAt to a temp variable....

+3  A: 
hasseg
A: 

Depends on the internal structure of your collection. If your collection is stored as an Array then you can use properities to achieve a square bracket effect:


/*** MyCollection class ***/
private var elementHolder : Array;

public function get getElementAt() : Array{
   return elementHolder;
}
/*** Some other class******/
public function main() : void{
   trace("Element at 3: " + myCollection.getElementAt[3] );
}

If your collection is not stored in an array maybe you can convert it to an array (like the java Collection's toArray() method).

for example, if your collection is a linked list:


/*** MyCollection class ***/

public function get getElementAt() : Array{
   var temp : Array = new Array();
   while( node.next != null{
      temp.push( node );
   }
   return temp;
}
/*** Some other class******/
public function main() : void{
   trace("Element at 3: " + myCollection.getElementAt[3] );
}
ForYourOwnGood