v2
This commit is contained in:
+38
@@ -0,0 +1,38 @@
|
||||
export class Doc {
|
||||
constructor(args = [], closed = {}) {
|
||||
this.content = [];
|
||||
this.indent = 0;
|
||||
this.args = args;
|
||||
this.closed = closed;
|
||||
}
|
||||
// the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it
|
||||
indented(fn) {
|
||||
this.indent += 1;
|
||||
try {
|
||||
fn(this);
|
||||
}
|
||||
finally {
|
||||
this.indent -= 1;
|
||||
}
|
||||
}
|
||||
write(arg) {
|
||||
if (typeof arg === "function") {
|
||||
arg(this, { execution: "sync" });
|
||||
arg(this, { execution: "async" });
|
||||
return;
|
||||
}
|
||||
const content = arg;
|
||||
const lines = content.split("\n").filter((x) => x);
|
||||
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
|
||||
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
|
||||
for (const line of dedented) {
|
||||
this.content.push(line);
|
||||
}
|
||||
}
|
||||
compile() {
|
||||
const F = Function;
|
||||
const content = this?.content ?? [``];
|
||||
const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`);
|
||||
return factory(...Object.values(this.closed));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user