sync-playground/sync/crdt/tiny-lww.ts

31 lines
854 B
TypeScript

import { PeerId, Primitive, Tid } from "../common.ts";
export class TinyLWW<Shape extends Record<string, Primitive>> {
values: Partial<Shape> = {};
lastWriters = new Map<keyof Shape, PeerId>();
clock = new Map<PeerId, Tid>();
set<K extends keyof Shape, V extends Shape[K]>(
key: K,
value: V,
from: PeerId,
at?: Tid,
): boolean {
const lastWriter = this.lastWriters.get(key);
at ??= lastWriter ? this.clock.get(lastWriter) : undefined;
at ??= -1;
if (lastWriter !== undefined && (this.clock.get(lastWriter) ?? -1) >= at) return false;
if ((this.clock.get(from) ?? -1) >= at) return false;
this.values[key] = value;
this.clock.set(from, at);
this.lastWriters.set(key, from);
return true;
}
get<K extends keyof Shape>(key: K): Shape[K] | undefined {
return this.values[key];
}
}