1.6 KiB
1.6 KiB
lww-register
(no submodules)
Purpose
Provides LWWRegister<T>, a Last-Write-Wins Register CRDT. The register holds a single value; when two replicas have different values, the one with the higher timestamp wins during merge. Ties are broken by node ID lexicographic order, ensuring deterministic convergence.
Features
set(value, timestamp?)— sets the value with optional explicit timestamp (defaults toDate.now())get()— returns the current value orundefinedmerge(state)— higher timestamp wins; tie-broken by nodeId lexicographic ordertoJSON()/fromJSON()— serialization round-tripclone()— deep copy
Usage: Basic Example
import { LWWRegister } from "@suaveplan/crdt";
const reg = new LWWRegister<string>("node-1");
reg.set("hello");
console.log(reg.get()); // "hello"
Usage: Advanced Example
import { LWWRegister } from "@suaveplan/crdt";
const a = new LWWRegister<number>("n1");
a.set(42, 1000);
const b = new LWWRegister<number>("n2");
b.set(99, 2000);
a.merge(b.state());
console.log(a.get()); // 99 (higher timestamp)
API Reference
LWWRegister<T>
constructor(nodeId, id?)— nodeId is required for tie-breakingset(value, timestamp?)— sets value with timestampget(): T | undefined— current valuemerge(state: LWWRegisterState<T>): void
Implementation Notes
Wall-clock timestamps from Date.now() can cause issues if clocks are not synchronized. For distributed deployments, use a monotonic or hybrid logical clock and pass the timestamp explicitly via set(value, timestamp).