UNPKG

1.4 kBJavaScriptView Raw
1/**
2 * This class allows a large text string to be constructed incrementally by appending small chunks. The final
3 * string can be obtained by calling StringBuilder.toString().
4 *
5 * @remarks
6 * A naive approach might use the `+=` operator to append strings: This would have the downside of copying
7 * the entire string each time a chunk is appended, resulting in `O(n^2)` bytes of memory being allocated
8 * (and later freed by the garbage collector), and many of the allocations could be very large objects.
9 * StringBuilder avoids this overhead by accumulating the chunks in an array, and efficiently joining them
10 * when `getText()` is finally called.
11 */
12var StringBuilder = /** @class */ (function () {
13 function StringBuilder() {
14 this._chunks = [];
15 }
16 /** {@inheritdoc IStringBuilder.append} */
17 StringBuilder.prototype.append = function (text) {
18 this._chunks.push(text);
19 };
20 /** {@inheritdoc IStringBuilder.toString} */
21 StringBuilder.prototype.toString = function () {
22 if (this._chunks.length === 0) {
23 return '';
24 }
25 if (this._chunks.length > 1) {
26 var joined = this._chunks.join('');
27 this._chunks.length = 1;
28 this._chunks[0] = joined;
29 }
30 return this._chunks[0];
31 };
32 return StringBuilder;
33}());
34export { StringBuilder };
35//# sourceMappingURL=StringBuilder.js.map
\No newline at end of file