stringAccumulator.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. export class StringAccumulator {
  2. lines: Line[];
  3. constructor() {
  4. this.lines = [new Line()];
  5. }
  6. get lastLine(): Line {
  7. return this.lines.at(-1) as Line;
  8. }
  9. add(token: string) {
  10. if (!token) {
  11. return;
  12. }
  13. this.lastLine.add(token);
  14. }
  15. space() {
  16. this.lastLine.add(SPACE);
  17. }
  18. break() {
  19. const newLine = new Line();
  20. newLine.indentTo(this.lastLine.indentation);
  21. this.lines.push(newLine);
  22. }
  23. indent() {
  24. this.lastLine.indent();
  25. }
  26. unindent() {
  27. this.lastLine.unindent();
  28. }
  29. indentTo(level: number = 1) {
  30. this.lastLine.indentTo(level);
  31. }
  32. toString(maxLineLength: number = DEFAULT_MAX_LINE_LENGTH) {
  33. let output: Line[] = [];
  34. this.lines.forEach(line => {
  35. if (line.textLength <= maxLineLength) {
  36. output.push(line);
  37. return;
  38. }
  39. const splitLines: Line[] = [new Line([], line.indentation)];
  40. let tokenIndex = 0;
  41. while (tokenIndex < line.tokens.length) {
  42. const incomingToken = line.tokens.at(tokenIndex) as string;
  43. const totalLength = (splitLines.at(-1) as Line).textLength + incomingToken.length;
  44. if (totalLength <= maxLineLength) {
  45. splitLines.at(-1)?.add(incomingToken);
  46. } else {
  47. splitLines.push(new Line([incomingToken], line.indentation + 1));
  48. }
  49. tokenIndex += 1;
  50. }
  51. output = [...output, ...splitLines.filter(splitLine => !splitLine.isEmpty)];
  52. });
  53. return output.join(NEWLINE).trim();
  54. }
  55. }
  56. const DEFAULT_MAX_LINE_LENGTH = 100;
  57. class Line {
  58. tokens: string[];
  59. indentation: number;
  60. constructor(tokens: string[] = [], indentation: number = 0) {
  61. this.tokens = tokens;
  62. this.indentation = indentation;
  63. }
  64. get isEmpty() {
  65. return this.toString().trim() === '';
  66. }
  67. get length() {
  68. return this.toString().length;
  69. }
  70. get textLength() {
  71. return this.toString().trim().length;
  72. }
  73. add(token: string) {
  74. this.tokens.push(token);
  75. }
  76. indent() {
  77. this.indentation += 1;
  78. }
  79. unindent() {
  80. this.indentation -= 1;
  81. }
  82. indentTo(level: number) {
  83. this.indentation = level;
  84. }
  85. toString() {
  86. return `${INDENTATION.repeat(this.indentation)}${this.tokens.join('').trimEnd()}`;
  87. }
  88. }
  89. const SPACE = ' ';
  90. const INDENTATION = ' ';
  91. const NEWLINE = '\n';