All files / json-crdt-patch/codec/clock ClockDecoder.ts

90% Statements 18/20
0% Branches 0/2
100% Functions 4/4
100% Lines 16/16

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 33156x   156x   8420x       2168x 2168x 27746x 2168x       8420x 8420x       124965x 124965x 124965x       1068363x 1068363x 1068363x 1068363x      
import {type ITimestampStruct, ClockVector, ts} from '../../clock';
 
export class ClockDecoder {
  /** Clock session index to logical clock. */
  protected readonly table: ITimestampStruct[] = [];
  public readonly clock: ClockVector;
 
  public static fromArr(arr: number[]): ClockDecoder {
    const decoder = new ClockDecoder(arr[0], arr[1]);
    const length = arr.length;
    for (let i = 2; i < length; i += 2) decoder.pushTuple(arr[i], arr[i + 1]);
    return decoder;
  }
 
  public constructor(sid: number, time: number) {
    this.clock = new ClockVector(sid, time + 1);
    this.table.push(ts(sid, time));
  }
 
  public pushTuple(sid: number, time: number) {
    const id = ts(sid, time);
    this.clock.observe(id, 1);
    this.table.push(id);
  }
 
  public decodeId(sessionIndex: number, timeDiff: number): ITimestampStruct {
    Iif (!sessionIndex) return ts(0, timeDiff);
    const clock = this.table[sessionIndex - 1];
    Iif (!clock) throw new Error('INVALID_CLOCK_TABLE');
    return ts(clock.sid, clock.time - timeDiff);
  }
}