first commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
# lww-register
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## 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 to `Date.now()`)
|
||||
- `get()` — returns the current value or `undefined`
|
||||
- `merge(state)` — higher timestamp wins; tie-broken by nodeId lexicographic order
|
||||
- `toJSON()` / `fromJSON()` — serialization round-trip
|
||||
- `clone()` — deep copy
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```ts
|
||||
import { LWWRegister } from "@suaveplan/crdt";
|
||||
|
||||
const reg = new LWWRegister<string>("node-1");
|
||||
reg.set("hello");
|
||||
console.log(reg.get()); // "hello"
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```ts
|
||||
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-breaking
|
||||
- `set(value, timestamp?)` — sets value with timestamp
|
||||
- `get(): T | undefined` — current value
|
||||
- `merge(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)`.
|
||||
Reference in New Issue
Block a user