Gustavo
Gustavo

Reputation: 1683

Extending indexOf to work with character code in AS3

One of my classes need this simple function to work:

private function indexOfCode(txt:String, charcode:int, ini:int=0):int {
        for(var i:int=ini; i<txt.length; i++){
            if(txt.charCodeAt(i)==charcode) return i;
        }
        return -1;
    }

Just like String.indexOf, but searching for a code (I'm searching for control codes like line feed).

In JavaScript I'd extend String class using prototype. In AS3 it seams this is an "old fashion" practice, but creating another custom class for a custom class seams to much. Is there a simple way to extend String? Any other suggestion?

Upvotes: 1

Views: 308

Answers (2)

Raja Jaganathan
Raja Jaganathan

Reputation: 36127

Please make sure that your prototype code complier need to crossed/execute at least once before call prototype functions.

String.prototype.indexOfCode = function(txt:String, charcode:int, ini:int=0):int
{
    for(var i:int=ini; i<txt.length; i++)
    {
      if(txt.charCodeAt(i)== charcode) return i;
    }

    return -1;
}


var letters:String = "ABCDEFG";
trace("indexOfCode :: " + letters.indexOfCode(letters,67,0)); //Complier error if strict mode
trace("indexOfCode :: " + letters["indexOfCode"](letters,67,0)); //No error

Problem:

  1. dynamic instance variable isn’t added until runtime;
  2. The compiler has no idea that it exists and will generate an error if it is used in strict mode and better you can avoid prototype functions.

Basically we can't extend String class because it is sealed class in actionscript.

Upvotes: 0

you can do it via some class with static method e.g. StringUtils.indexOfCode(); or you could make global function like so:

package
{
    public function indexOfCode(txt:String, charcode:int, ini:int=0):int
    {
        for(var i:int=ini; i<txt.length; i++)
        {
            if(txt.charCodeAt(i)==charcode) return i;
        }
        return -1;
    }
}

Upvotes: 1

Related Questions