Build state-based CRDTs: a PN-counter, an add-wins OR-Set without tombstones and a last-writer-wins map
Problem
Offline-first apps, such as notes and to-do apps, let several devices change the same data without a server in the middle of every edit, then sync later. CRDTs (conflict-free replicated data types) make that safe: every replica keeps a state, states are sent around in any order, any number of times, and merge always brings replicas to the same value. Build three state-based CRDTs for a shared shopping list.
const phone = new ORSet("phone");
const laptop = new ORSet("laptop");
phone.add("milk");
laptop.merge(phone.state());
phone.remove("milk"); // removes the milk it has seen
laptop.add("milk"); // concurrently adds milk again
phone.merge(laptop.state());
phone.has("milk"); // true: add winsRef. UR-1449 · © UIRound · uiround.com/questions/build-state-based-crdts-a-pn-counter-an-add-wins-or-set-without-tombstones-and-a-last-writer-wins-map
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 3
- code listings
- 6
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1A state-based CRDT is a state plus a merge that is commutative, associative and idempotent, so replicas converge however often and in whatever order states are exchanged. For counters, keep one grow-only number per replica and merge with max per replica.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.