json-joy
Version:
Collection of libraries for building collaborative editing apps.
41 lines (40 loc) • 1.29 kB
JavaScript
import { printTs } from './clock';
export class Batch {
patches;
constructor(patches) {
this.patches = patches;
}
getId() {
if (!this.patches.length)
return undefined;
return this.patches[0].getId();
}
rebase(serverTime) {
const id = this.getId();
if (!id)
throw new Error('BATCH_EMPTY');
const transformHorizon = id.time;
const patches = this.patches;
const length = patches.length;
const newPatches = [];
for (let i = 0; i < length; i++) {
const patch = patches[i];
newPatches.push(patch.rebase(serverTime, transformHorizon));
serverTime += patch.span();
}
return new Batch(newPatches);
}
clone() {
return new Batch(this.patches.map((patch) => patch.clone()));
}
toString(tab = '') {
const id = this.getId();
let out = `Batch ${id ? printTs(id) : '(nil)'}\n`;
for (let i = 0; i < this.patches.length; i++) {
const patch = this.patches[i];
const isLast = i === this.patches.length - 1;
out += `${tab}${isLast ? '└─' : '├─'} ${patch.toString(tab + `${isLast ? ' ' : '│'} `)}\n`;
}
return out;
}
}