Return to Snippet

Revision: 22425
at January 12, 2010 11:37 by aadsm


Initial Code
ByteArray.prototype.indexOf = Array.prototype.indexOf;
ByteArray.prototype.replace = function(searchBytes, replaceBytes)
{
    searchBytes = searchBytes instanceof Array ? searchBytes : [searchBytes];
    replaceBytes = replaceBytes instanceof Array ? replaceBytes : (replaceBytes === undefined ? [] : [replaceBytes]);
    if( searchBytes.length == 0 ) { return; }
    
    var ix;
    var lastIndex = 0;
    var spliceArgs = [-1, searchBytes.length].concat(replaceBytes);
    
    while( (ix = this.indexOf(searchBytes[0])) >= 0 )
    {
        var i = 0;
        
        while( ++i < searchBytes.length && this[ix+i] == searchBytes[i] );
        if( i < searchBytes.length ) { lastIndex = ix+1; continue; }
        
        // it's a match!!
        spliceArgs[0] = ix;
        Array.prototype.splice.apply( this, spliceArgs );
        ix += replaceBytes.length;
    }
    
    return this;
}

Initial URL

                                

Initial Description

                                

Initial Title
ByteArray.replace

Initial Tags
replace

Initial Language
JavaScript