doc.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. export class Doc {
  2. constructor(args = []) {
  3. this.content = [];
  4. this.indent = 0;
  5. if (this)
  6. this.args = args;
  7. }
  8. indented(fn) {
  9. this.indent += 1;
  10. fn(this);
  11. this.indent -= 1;
  12. }
  13. write(arg) {
  14. if (typeof arg === "function") {
  15. arg(this, { execution: "sync" });
  16. arg(this, { execution: "async" });
  17. return;
  18. }
  19. const content = arg;
  20. const lines = content.split("\n").filter((x) => x);
  21. const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
  22. const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
  23. for (const line of dedented) {
  24. this.content.push(line);
  25. }
  26. }
  27. compile() {
  28. const F = Function;
  29. const args = this?.args;
  30. const content = this?.content ?? [``];
  31. const lines = [...content.map((x) => ` ${x}`)];
  32. // console.log(lines.join("\n"));
  33. return new F(...args, lines.join("\n"));
  34. }
  35. }