universal-common
Version:
Library that provides useful missing base class library functionality.
73 lines (66 loc) • 2.01 kB
JavaScript
import Environment from "./Environment.js";
/**
* A mutable string class that provides an efficient way to build strings.
* Similar to StringBuilder in C# or StringBuffer in Java.
*/
export default class StringBuilder {
/**
* The internal string being built.
* @type {string}
*/
#string;
/**
* Creates a new StringBuilder instance.
* @param {string} [string] - The initial string value. Default is an empty string.
*/
constructor(string) {
if (typeof(string) === "string") {
this.#string = string;
}
else {
this.#string = "";
}
}
/**
* Gets the length of the current string.
* @returns {number} The number of characters in the current string.
*/
get length() {
return this.#string.length;
}
/**
* Appends the string representation of an object to the end of the current string.
* @param {*} object - The object to append.
* @returns {void}
*/
append(object) {
this.#string += object.toString();
}
/**
* Appends the string representation of an object followed by a line terminator to the end of the current string.
* @param {*} [object] - The object to append. If not provided, only a line terminator is appended.
* @returns {void}
*/
appendLine(object) {
if (object) {
this.#string += object.toString() + Environment.newLine;
}
else {
this.#string += Environment.newLine;
}
}
/**
* Removes all characters from the current StringBuilder instance.
* @returns {void}
*/
clear() {
this.#string = "";
}
/**
* Returns the string representation of the current StringBuilder instance.
* @returns {string} The string representation of the current StringBuilder.
*/
toString() {
return this.#string;
}
}