hardReact Native#138

G-Counter CRDT for offline sync

Prompt

Implement a G-Counter (Grow-only Counter) CRDT for an offline-first Expo/React Native app.

A G-Counter is a Conflict-free Replicated Data Type where each replica (e.g. a device with an Expo SecureStore-assigned replicaId) tracks its own increments in a private slot. Counters are persisted locally (AsyncStorage / expo-sqlite) and merged whenever the device reconnects — taking element-wise max guarantees the replicas converge without a server or consensus. The total value is the sum of all slots.

Write four functions:

  1. createGCounter(replicaCount) — return an array of replicaCount zeros
  2. increment(counter, replicaId) — return a new counter with slot replicaId incremented by 1
  3. merge(counterA, counterB) — return a new counter where each slot is Math.max of the two
  4. value(counter) — return the sum of all slots

Hints

Solution

Your Code

15 min

Tests

Click Run to test your code