UNPKG

json-joy

Version:

Collection of libraries for building collaborative editing apps.

63 lines (62 loc) 2.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClockTable = exports.ClockTableEntry = void 0; const clock_1 = require("../../clock"); class ClockTableEntry { constructor(index, id) { this.index = index; this.id = id; } } exports.ClockTableEntry = ClockTableEntry; class ClockTable { constructor() { this.bySid = new Map(); this.byIdx = []; } static from(clock) { const table = new ClockTable(); table.push(new clock_1.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 clock_1.Timestamp(reader.vu57(), reader.vu57())); for (let i = 1; i < length; i++) clockTable.push(new clock_1.Timestamp(reader.vu57(), reader.vu57())); return clockTable; } 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 clock_1.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); } } } exports.ClockTable = ClockTable;