All files / builder/util raw-updater.ts

100% Statements 26/26
93.33% Branches 14/15
100% Functions 6/6
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 501x             1x   904x 231x     231x 231x     231x     684x 4x 4x 680x 676x 4x 4x     684x 8x   684x 676x 676x 8x 4x   684x   231x     684x            
import {
  Change,
  DeleteChange,
  InsertChange,
  ReplaceChange,
} from 'cyia-code-util';
 
export class RawUpdater {
  static update(content: string, change: Change[]) {
    change = change.sort((a, b) => b.start - a.start);
    return new RawUpdater(content, change).update();
  }
  originContent!: string;
  constructor(private content: string, private changes: Change[]) {
    this.originContent = content;
  }
  update() {
    this.changes.forEach((change) => {
      let deleteChange: DeleteChange | undefined;
      let insertChange: InsertChange | undefined;
      if (change instanceof ReplaceChange) {
        insertChange = new InsertChange(change.start, change.content);
        deleteChange = new DeleteChange(change.start, change.length);
      } else if (change instanceof InsertChange) {
        insertChange = change;
      } else Eif (change instanceof DeleteChange) {
        deleteChange = change;
      }
      let list!: [string, string];
      if (deleteChange) {
        list = this.slice(deleteChange.start, deleteChange.length);
      }
      if (!list && insertChange) {
        list = this.slice(insertChange.start);
        list.splice(1, 0, insertChange.content);
      } else if (insertChange) {
        list.splice(1, 0, insertChange.content);
      }
      this.content = list.join('');
    });
    return this.content;
  }
  private slice(pos: number, length: number = 0): [string, string] {
    return [
      this.content.substring(0, pos),
      this.content.substring(pos + length),
    ];
  }
}