fracturedjsonjs
Version:
JSON formatter that produces highly readable but fairly compact output
65 lines (64 loc) • 2.07 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringJoinBuffer = void 0;
/**
* A place where strings are piled up sequentially to eventually make one big string.
*/
class StringJoinBuffer {
constructor() {
this._lineBuff = [];
this._docBuff = [];
}
/**
* Add zero or more strings to the buffer.
*/
Add(...values) {
this._lineBuff.push(...values);
return this;
}
/**
* Add the requested number of spaces.
*/
Spaces(count) {
const spacesStr = (count < StringJoinBuffer.SPACES_CACHE.length)
? StringJoinBuffer.SPACES_CACHE[count]
: ' '.repeat(count);
this._lineBuff.push(spacesStr);
return this;
}
/**
* Used to indicate the end of a line. Triggers special processing like trimming whitespace.
*/
EndLine(eolString) {
this.AddLineToWriter(eolString);
return this;
}
/**
* Call this to let the buffer finish up any work in progress.
*/
Flush() {
this.AddLineToWriter("");
return this;
}
/**
* Converts the buffer's contents into a single string.
*/
AsString() {
// I experimented with a few approaches to try to make this faster, but none of them made much difference
// for an 8MB file. Turns out Array.join is really quite good.
return this._docBuff.join("");
}
/**
* Takes the contents of _lineBuff and merges them into a string and adds it to _docBuff. We trim trailing
* whitespace in the process.
*/
AddLineToWriter(eolString) {
if (this._lineBuff.length === 0 && eolString.length === 0)
return;
let line = this._lineBuff.join("").trimEnd();
this._docBuff.push(line + eolString);
this._lineBuff = [];
}
}
exports.StringJoinBuffer = StringJoinBuffer;
StringJoinBuffer.SPACES_CACHE = Array.from({ length: 64 }, (_, i) => " ".repeat(i));