Ted Patrick > { Events & Community } > Adobe Systems


IArray - Iterator Array

I am a big believer in making things simple. I wrote this class a while back to simplify looping over array contents. It makes looping over an array easy, much more logical, and less prone to error.&

The IArray class can be found here:

http://www.powersdk.com/sample/IArray.zip

To loop over an IArray's content you simply pass a function or method to the 'iterate' method as follows:

//create an IArray
a = new IArray()

//add some items to the IArray
a[0] = 'Zero'
a[1] = 'One'
a[2] = 'Two'
a[3] = 'Three'
a[4] = 'Four'
a[5] = 'Five'


//create a function
f = function( a , b ){trace( a + ' ' + b )}

//iterate over the IArray
a.iterate( f )

The iterate method will call the passed function with 2 arguments, rowNumber and rowObject allowing your function to do as it pleases.

You can also iterate over the items in reverse:

//iterate over the IArray and set the reverse flag to true (default is false)
a.iterate( f , true )


You can also iterate and modify the scope of passed function:

//iterate over the IArray forward in the scope of _level0
a.iterate( f , false , _level0 )

I find that it removes gobs of for..in, for, and while loops from dependent classes and makes iteration over an array much simpler and predictable. Plus since it works consistantly, your dependent code is less prone to error. All you need is to pass a function to iterate and off it goes.

Cheers,

Ted ;)

5 Responses to “ IArray - Iterator Array ”

  1. # Anonymous Anonymous

    This post has been removed by a blog administrator.  

  2. # Anonymous Anonymous

    Very good, I've always thought to myself I should write something like that but never got around to it. What are your thoughts on making a global function rather than a class, so you could use it on existing arrays. Something like:

    IterateArray(array,function,reverse,scope)  

  3. # Blogger Ted Patrick

    There are 100's of ways to do it. None are wrong, only different.

    I prefer to use a subclass as it allows for better encapsulation and reuse.

    myDataGrid.dataprovider = new IArray()

    With this 'iterate' is within the component itself.

    Who am I to judge what works for others? If you like it, do it. Try different methodologies and figure out what works best with your style. Everyone works differently and that is ok!

    Cheers,

    ted ;)  

  4. # Anonymous Anonymous

    Thanks for the insight, I really appreciate it!  

  5. # Blogger Abdul

    Hi Ted-

    Looking at just IArray, I first thought its some kind interface because of that "I" out there.... But it was clear when I saw usage....

    Anyways! Nice work as usual...

    cheers,

    -abdul  

Post a Comment



© 2008 Ted On Flash

Technorati Profile