lightsb
Version:
Simple light string builder
88 lines (87 loc) • 2.7 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringBuilder = exports.OutOfRangeError = void 0;
class OutOfRangeError extends Error {
}
exports.OutOfRangeError = OutOfRangeError;
class StringBuilder {
constructor(content, capacity) {
if (capacity != undefined && capacity < 0) {
throw new Error("`capacity` should not be less than 0.");
}
this.capacity = capacity;
this.append(content);
}
setCapacity(capacity) {
if (capacity != undefined && capacity < 0) {
throw new Error("`capacity` should not be less than 0.");
}
this.capacity = capacity;
if (this.capacity && this.content && this.content.length > this.capacity) {
this.content = this.content.substring(0, this.content.length - this.capacity - 1);
}
return this;
}
append(content) {
if (!content) {
return this;
}
if (this.content == undefined) {
this.content = "";
}
const strContent = String(content);
if (this.capacity != undefined) {
const newContentSize = this.content.length + strContent.length;
if (newContentSize > this.capacity) {
throw new OutOfRangeError(`Content length is greater than the maximum capacity (${newContentSize}/${this.capacity})`);
}
}
this.content += strContent;
return this;
}
appendRepeat(content, count) {
if (count < 0) {
throw new Error("`count` should not be less than 0.");
}
for (let i = 0; i < count; i++) {
this.append(content);
}
return this;
}
appendLine(content) {
return this.append(`${content}\n`);
}
appendLineRepeat(content, count) {
return this.appendRepeat(`${content}\n`, count);
}
appendLines(...contents) {
return this.appendLine(contents.join("\n"));
}
appendEmptyLine() {
return this.append("\n");
}
appendEmptyLines(count) {
return this.appendRepeat("\n", count);
}
setContent(content) {
return this.clear().append(content);
}
clear() {
this.content = undefined;
return this;
}
substring(start, end) {
var _a;
return (_a = this.content) === null || _a === void 0 ? void 0 : _a.substring(start, end);
}
isEmpty() {
return this.content == undefined || this.content.length == 0;
}
equals(other) {
return this.content == other;
}
toString() {
return this.content;
}
}
exports.StringBuilder = StringBuilder;