Search Box

Google
 

Thursday, March 08, 2007

Adding and removing Strings in ActionScript.

It's been a long time since i was hanging around with BitmapData and now for a change i am going to write about one of the primitive datatype of ActionScript called "String". Today i am going to discuss with a story about why we should focus on using methods that have been shipped with the native classes rather than writing flash loops and achieve the same.

Today my colleague came rushing to me to show his new prototype he had written for String class. The reason he came to me was that i am known for optimizing codes(do not blame me for this) and hence he wanted me to take a glance of his code and suggest necessary modifications wherever applicable. But to his dismay and disappointment slowly his face started to grow smaller and smaller as we sat down to modify his code (he must have been thinking "oh my god why did i ask this guy anyway).

Still wondering what am i talking about ? Let me take the pleasure of telling you what happened. In one of the application my friend was developing he had a requirement of adding and removing strings. The scenario was like this, a word is passed to a custom method written as a prototype as an argument which needs to be added to the existing string if it does not exist. Else if the particular word already exists then remove it.

hmmmmm, nice requirement i would say and below is the code written by my friend .




String.prototype.appendAndRemove = function(remStr:String):String
{
var tempArr:Array = this.split(remStr);
trace('arr : '+this.indexOf(remStr));
if(tempArr.length >=2)
{
var tempArr1:Array = this.split(remStr+' ');
this = '';
for(i=0;ilength;i++)
{
this += (tempArr1[i].length !=0)?tempArr1[i]:'';
}

}
this += (tempArr.length != 2)?remStr+' ':'';s;
return this;
}


Looking at the code anybody can understand what the developer had intended to do and moreover the name itself suggests sharply about its use. okay let us ask achilles what he has to say about this.

I would say we could have avoided the loop that's been used in the code and rather used the .join method instead. Below is my version of code which does the same thing as the above code and coincidentally has the same bug the above one has(find it out yourself about what the bug is).



String.prototype.appendAndRemove = function(remStr:String):String
{
return (this = (this.indexOf(remStr) == -1)?this+remStr:this.split(remStr).join(''));
}



Hey wait do not conclude i am bluffing and believe me both the version of codes literally do the same thing. If you still do not believe go ahead and check it out yourself.

Meanwhile let's meet you all in some time soon.

Regards,

Ashok Srinivasan.