UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

58 lines (57 loc) 1.83 kB
import { Timestamp } from '../../clock'; export class ClockTableEntry { index; id; constructor(index, id) { this.index = index; this.id = id; } } export class ClockTable { static from(clock) { const table = new ClockTable(); table.push(new Timestamp(clock.sid, clock.time - 1)); // biome-ignore lint: using .forEach() on Map is the fastest way to iterate clock.peers.forEach((id) => table.push(id)); return table; } static decode(reader) { const clockTable = new ClockTable(); const length = reader.vu57(); clockTable.push(new Timestamp(reader.vu57(), reader.vu57())); for (let i = 1; i < length; i++) clockTable.push(new Timestamp(reader.vu57(), reader.vu57())); return clockTable; } bySid = new Map(); byIdx = []; parseField(field) { const underscoreIndex = field.indexOf('_'); const relativeSid = Number.parseInt(field.slice(0, underscoreIndex), 36); const time = Number.parseInt(field.slice(underscoreIndex + 1), 36); const clock = this.byIdx[relativeSid]; return new Timestamp(clock.sid, time); } push(id) { const byIdx = this.byIdx; const index = byIdx.length; byIdx.push(id); this.bySid.set(id.sid, new ClockTableEntry(index, id)); } getBySid(sid) { const entry = this.bySid.get(sid); if (!entry) throw new Error('CLOCK_NOT_FOUND'); return entry; } write(writer) { const table = this.byIdx; const length = table.length; writer.vu57(length); for (let i = 0; i < length; i++) { const clock = table[i]; writer.vu57(clock.sid); writer.vu57(clock.time); } } }