javascriptアナログC莾中のSteringBuiderは、JS中の文字列のつなぎ合わせの効率と性能を向上させます.

2514 ワード

/*
  Array  join     C#  StringBuilder,  JS            。
   JS    StringBuilder.js      ,
                                 
Author : panwb 
Date   : 2012-11-29
*/
function StringBuilder(str)
{
    //     
	this.arrstr = (str === undefined ? new Array() : new Array(str.toString()));

    //     (    newstr               length)
	this.length = (str === undefined ? 0 : str.length);

    //        ,   C#  StringBuilder.Append  
	this.append = StringBuilder_append;

    //        ,   C#  StringBuilder.AppendFormat  
	this.appendFormat = StringBuilder_appendFormat;

    //  toString()  
	this.toString = StringBuilder_toString;

    //  replace()  
	this.replace = StringBuilder_replace;

    //  remove()  
	this.remove = StringBuilder_remove;

    //            
    this.clear = StringBuilder_clear;
}

//        ,   C#  StringBuilder.Append  
function StringBuilder_append(f)
{
    if (f === undefined || f === null)
    {
        return this;
    }

    this.arrstr.push(f);
    this.length += f.length;
    return this;
}

//        ,   C#  StringBuilder.AppendFormat  
function StringBuilder_appendFormat(f)
{
    if (f === undefined || f === null)
    {
        return this;
    }

    //    ,  replace                    
    var params = arguments;
    
    var newstr = f.toString().replace(/\{(\d+)\}/g,
        function (i, h) { return params[parseInt(h, 10) + 1]; });
    this.arrstr.push(newstr);
    this.length += newstr.length;
    return this;
}

//  toString()  
function StringBuilder_toString()
{
    return this.arrstr.join('');
}

//  replace()  
function StringBuilder_replace()
{
    if (arguments.length >= 1)
    {
        var newstr = this.arrstr.join('').replace(arguments[0], arguments[1]);
        this.arrstr.length = 0;
        this.length = newstr.length;
        this.arrstr.push(newstr);
    }
    return this;
}

//  remove()  
function StringBuilder_remove()
{
    if (arguments.length > 0)
    {
        var oldstr = this.arrstr.join('');
        var substr = (arguments.length >= 2 ?
            oldstr.substring(arguments[0], arguments[1]) : oldstr.substring(arguments[0]));
        var newstr = oldstr.replace(substr, "");
        this.arrstr.length = 0;
        this.length = newstr.length;
        this.arrstr.push(newstr);
    }
    return this;
}

//            
function StringBuilder_clear()
{
    this.arrstr.length = 0;
    this.length = 0;
    return this;
}
貴重なご意見を歓迎します.一緒に改善を検討します.