Return to Snippet

Revision: 42553
at March 7, 2011 08:35 by gdesjardins


Initial Code
function StringBuilder(){
    // (C) Andrea Giammarchi - Mit Style License
    //	http://webreflection.blogspot.com/2008/06/lazy-developers-stack-concept-and.html
    if(arguments.length)
        this.append.apply(this, arguments);
};
StringBuilder.prototype = function(){
    var join = Array.prototype.join,
        slice = Array.prototype.slice,
        RegExp = /\{(\d+)\}/g,
        toString = function(){return join.call(this, "")};
    return {
        constructor:StringBuilder,
        length:0,
        append:Array.prototype.push,
        appendFormat:function(String){
            var i = 0, args = slice.call(arguments, 1);
            this.append(RegExp.test(String) ?
                String.replace(RegExp, function(String, i){return args[i]}):
                String.replace(/\?/g, function(){return args[i++]})
            );
            return  this;
        },
        size:function(){return this.toString().length},
        toString:toString,
        valueOf:toString
    }
}();

//usage
/*
var str = new StringBuilder("a", "b", "c");
str.append("de", "f");
alert(str.length); // 5
alert(str.size()); // 6, the length of the string
alert(str); // abcdef

alert(
    new StringBuilder("a", "b", "c").
    appendFormat("{0}{1}{0}", 0, 1).
    appendFormat("???", 1, 2, 3)
);
// abc010123

*/

Initial URL
http://webreflection.blogspot.com/2008/06/lazy-developers-stack-concept-and.html

Initial Description

                                

Initial Title
js StringBuilder

Initial Tags
javascript

Initial Language
JavaScript