Return to Snippet

Revision: 60027
at October 17, 2012 02:11 by jswaringen


Initial Code
/*****************************************************************
 * Stringbuilder Class - emulates the C#/VB.NET stringbuilder
 * @constructor
 *****************************************************************/
function StringBuilder() {
    var strings = [];

    this.append = function (string)
    {
        string = verify(string);
        if (string.length > 0) {
            strings[strings.length] = string;
        }
    };

    this.appendLine = function (string)
    {
        string = verify(string);
        if (this.isEmpty())
        {
            if (string.length > 0) {
                strings[strings.length] = string;
            }
            else {
                return;
            }
        }
        else {
            strings[strings.length] = string.length > 0 ? "
" + string : "
";
        }
    };

    this.clear = function () { strings = []; };

    this.isEmpty = function () { return strings.length == 0; };

    this.toString = function () { return strings.join(""); };

    var verify = function (string)
    {
        if (!defined(string)) {
            return "";
        }
        if (getType(string) != getType('string')) {
            return String(string);
        }
        return string;
    };

    var defined = function (el)
    {
        return el != null && typeof(el) != "undefined";
    };

    var getType = function (instance)
    {
        if (!defined(instance.constructor)) {
            throw new Error("Unexpected object type");
        }
        var type = String(instance.constructor).match(/function\s+(\w+)/);

        return defined(type) ? type[1] : "undefined";
    };
}

Initial URL

                                

Initial Description
Emulates the StringBuilder() function found in .NET Languages

Initial Title
JavaScript: StringBuilder

Initial Tags
javascript

Initial Language
JavaScript