Thursday, January 31, 2008

Get to Know Your Methods

No matter how experienced you are with a language, it's a good idea to frequently browse the documents. You can find useful methods that you hadn't used before...or at least not on a daily basis or even remotely recently.

In a personal project, I've got an array of references to MovieClips and I want to sort them based on the values of four properties attached to these objects. To be honest, I haven't done much array sorting on client-side since college. Simple sorting, yes. Sorting based on more than two properties, not so much. I usually do my sorting in a database query.

So, as I started to tackle the problem I imagined looping through the array with a function that would reposition each element based on the values of their four properties. If two elements had equivalent values for a property, compare the next property. Something like the following pseudo code

for length of array
{
if ( i.p1 < i-1.p1){
move i in front of i-1
else if(i.p1 == i-1.p1){
if(i.p2 < i-1.p2){
move i in front of i-1
} else if(i.p2 == i-1.p2){
. . .
}
}
}

I could be stubborn and develop this into a full method, or I could read the docs and notice the sortOn() method of the Array Class. Which might look like this

myArray.sortOn(["p1", "p2", "p3", "p4"], Array.NUMERIC | Array.DESCENDING);

which does the job quite nicely.

1 comments:

Sarma said...

this is so true! I've been using as from early beginnings, i naturally i have also used my "custom" made solutions, without even checking the docs for "what's new" or alike sections....
Once you get burned....