All files / collaborative-str/src MemoryEditor.ts

47.5% Statements 19/40
38.46% Branches 10/26
45.45% Functions 5/11
57.57% Lines 19/33

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68    1x 3x 3x 3x 3x 3x     3x               4x       2x 2x 2x       1x                   3x 3x 3x       2x 2x   2x         1x                              
import type {EditorFacade, EditorSelection, SimpleChange} from './types';
 
export class MemoryEditor0 implements EditorFacade {
  public __str: string = '';
  public __cursorStart: number = -1;
  public __cursorEnd: number = -1;
  public __cursorDirection: -1 | 0 | 1 = 0;
  public __onchange = () => {
    this.onchange?.();
  };
  public __onselection = () => {
    this.onselection?.();
  };
 
  onchange?: (change: SimpleChange[] | void) => void;
  onselection?: () => void;
 
  public get(): string {
    return this.__str;
  }
 
  public set(str: string): void {
    this.__str = str;
    Iif (this.__cursorStart > 0) this.__cursorStart = str.length;
    Iif (this.__cursorEnd > 0) this.__cursorEnd = str.length;
  }
}
 
export class MemoryEditor1 extends MemoryEditor0 {
  public getLength(): number {
    return this.__str.length;
  }
 
  public set(): void {
    throw new Error('.set() should not be needed');
  }
 
  public ins(position: number, text: string): void {
    this.__str = this.__str.slice(0, position) + text + this.__str.slice(position);
    Iif (this.__cursorStart > 0 && this.__cursorStart >= position) this.__cursorStart += text.length;
    Iif (this.__cursorEnd > 0 && this.__cursorEnd >= position) this.__cursorEnd += text.length;
  }
 
  public del(position: number, length: number): void {
    this.__str = this.__str.slice(0, position) + this.__str.slice(position + length);
    Iif (this.__cursorStart > 0 && this.__cursorStart >= position)
      this.__cursorStart -= Math.min(length, this.__cursorStart - position);
    Iif (this.__cursorEnd > 0 && this.__cursorEnd >= position)
      this.__cursorEnd -= Math.min(length, this.__cursorEnd - position);
  }
}
 
export class MemoryEditor2 extends MemoryEditor1 {
  getSelection?(): EditorSelection | null {
    if (this.__cursorStart < 0) return null;
    if (this.__cursorEnd < 0) return null;
    return [this.__cursorStart, this.__cursorEnd, this.__cursorDirection];
  }
 
  setSelection?(start: number, end: number, direction: -1 | 0 | 1): void {
    const length = this.__str.length;
    if (start > end) [start, end] = [end, start];
    this.__cursorStart = Math.max(0, Math.min(length, start));
    this.__cursorEnd = Math.max(0, Math.min(length, end));
    this.__cursorDirection = direction;
  }
}