treegen: Add a utility FileWriter class
This commit is contained in:
parent
d23a94f11b
commit
ff28963403
1 changed files with 49 additions and 0 deletions
49
treegen/src/util.ts
Normal file
49
treegen/src/util.ts
Normal file
|
@ -0,0 +1,49 @@
|
|||
|
||||
function isWhiteSpace(ch: string) {
|
||||
return /[\r\t ]/.test(ch);
|
||||
}
|
||||
|
||||
export interface FileWriterOptions {
|
||||
indentStr?: string;
|
||||
startIndent?: number;
|
||||
indentWidth?: number;
|
||||
}
|
||||
|
||||
export class FileWriter {
|
||||
|
||||
public currentText = '';
|
||||
|
||||
private atBlankLine = true;
|
||||
private currentIndent: number;
|
||||
private indentStr: string;
|
||||
private indentWidth: number;
|
||||
|
||||
constructor(opts: FileWriterOptions = {}) {
|
||||
this.indentStr = opts.indentStr ?? ' ';
|
||||
this.indentWidth = opts.indentWidth ?? 2;
|
||||
this.currentIndent = (opts.startIndent ?? 0) * this.indentWidth;
|
||||
}
|
||||
|
||||
public indent(count = 1) {
|
||||
this.currentIndent += this.indentWidth * count;
|
||||
}
|
||||
|
||||
public dedent(count = 1) {
|
||||
this.currentIndent -= this.indentWidth * count;
|
||||
}
|
||||
|
||||
public write(str: string) {
|
||||
for (const ch of str) {
|
||||
if (ch === '\n') {
|
||||
this.atBlankLine = true;
|
||||
} else if (!(this.atBlankLine && isWhiteSpace(ch))) {
|
||||
if (this.atBlankLine) {
|
||||
this.currentText += this.indentStr.repeat(this.currentIndent)
|
||||
}
|
||||
this.atBlankLine = false;
|
||||
}
|
||||
this.currentText += ch;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in a new issue