Iterator

Lately I’ve been finding that I use the iterator more and more. The Iterator is a design pattern that is used to iterate through the elements in an array. It provides a few features that make it a better choice than the typical loops that you might employ. The core concept is that the Iterator pattern is a class that returns each element in an Array. Forget writing all of those typical tired for loops and move on to a more streamlined pattern based system!

The Iterator provides a few advantages over the standard methods of looping through an Array. The Iterator pattern encapsulates the Array, prevent accidentally modifying the array. By making Iterators to access elements forward, reverse or randomly, accessing elements in the array in these ways becomes as easy as making an instance of any class.

The Iterator is built around three methods, hasNext, next and reset. The hasNext method returns true when there is a next item in the array. The next method increments the index and returns the next item. The reset method resets the index to 0 to start over again.

You might use the Iterator in this way.

var it:Iterator = new Iterator( array );
while( it.hasNext() ) {
	trace( it.next() );
}

The Iterator class itself might look like this:

package com.webdevils.utils {

	public class BasicIterator implements IIterator {
		private var _data:Array;
		private var _index:uint;

		public function BasicIterator( array:Array ) {
			_data = array;
			_index = 0;
		}

		public function reset():void {
			_index = 0;
		}

		public function hasNext():Boolean {
			return Boolean( _index < _data.length );
		}

		public function next():Object {
			return Object( _data[ _index ++  ] );
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *