package com.ericfeminella.collections
{
import mx.collections.CursorBookmark;
import mx.collections.ICollectionView;
import mx.collections.IViewCursor;
/**
*
* Concrete <code>Iterator</code> implementation which provides an API
* for iterating over an <code>ICollectionView</code>.
*
* @example The following is a basic <code>CollectionIterator</code>
* example:
*
* <listing version="3.0">
*
* var collection:ICollectionView = new ArrayCollection(["a","b","c"]);
* var it:Iterator = new CollectionIterator( collection );
*
* while ( it.hasNext() )
* {
* trace( it.next(), it.position() );
* }
*
* // a, 0
* // b, 1
* // c, 2
*
* </listing>
*
* @see com.ericfeminella.collections.Iterator
* @see http://livedocs.adobe.com/flex/3/langref/mx/collections/ICollectionView.html
* @see http://livedocs.adobe.com/flex/3/langref/mx/collections/CursorBookmark.html
* @see http://livedocs.adobe.com/flex/3/langref/mx/collections/IViewCursor.html
*
*/
public class CollectionIterator implements Iterator
{
/**
*
* Defines the <code>ICollectionView</code> instance
*
* @see http://livedocs.adobe.com/flex/3/langref/mx/collections/ICollectionView.html
*
*/
protected var collection:ICollectionView;
/**
*
* Defines the <code>IViewCursor</code> instance to the aggregate
*
* @see http://livedocs.adobe.com/flex/3/langref/mx/collections/IViewCursor.html
*
*/
protected var cursor:IViewCursor;
/**
*
* Contains the current indexed position in the collection
*
*/
protected var index:int;
/**
*
* Instantiates a new <code>CollectionIterator</code> instance
*
* @param the collection in which to iterate over
*
*/
public function CollectionIterator(collection:ICollectionView)
{
setCollection( collection );
}
/**
*
* Sets the collection in which to iterate over
*
* @param an ICollectionView instance
*
*/
public function setCollection(collection:ICollectionView) : void
{
this.collection = collection;
cursor = collection.createCursor();
}
/**
*
* Determines if there are elements remaining in the ICollectionView
*
* @return true if an element remains, false if not
*
*/
public function hasNext() : Boolean
{
var result:Boolean = true;
if ( cursor.beforeFirst || cursor.afterLast )
{
result = false;
}
return result;
}
/**
*
* Returns the next item in the ICollectionView
*
* @retrun an arbitrary object in the collection
*
*/
public function next() : *
{
var current:Object = cursor.current;
index = cursor.bookmark.getViewIndex();
cursor.moveNext();
return current;
}
/**
*
* Resets the IViewCursor to a zero based indexed position
*
* @see http://livedocs.adobe.com/flex/3/langref/mx/collections/CursorBookmark.html#FIRST
*
*/
public function reset() : void
{
cursor.seek( CursorBookmark.FIRST );
}
/**
*
* Determines the IViewCursor position of the ICollectionView
*
* @return the current position of the aggreagate
*
*/
public function position() : int
{
return index;
}
}
}