classLWWRegister<T>{readonly id:string;
state:[peer:string, timestamp:number, value:T];getvalue(){returnthis.state[2];}constructor(id:string, state:[string,number,T]){this.id = id;this.state = state;}set(value:T){// set the peer ID to the local ID, increment the local timestamp by 1 and set the valuethis.state =[this.id,this.state[1]+1, value];}merge(state:[peer:string, timestamp:number, value:T]){const[remotePeer, remoteTimestamp]= state;const[localPeer, localTimestamp]=this.state;// if the local timestamp is greater than the remote timestamp, discard the incoming valueif(localTimestamp > remoteTimestamp)return;// if the timestamps are the same but the local peer ID is greater than the remote peer ID, discard the incoming valueif(localTimestamp === remoteTimestamp && localPeer > remotePeer)return;// otherwise, overwrite the local state with the remote statethis.state = state;}}
classLWWMap<T>{readonly id:string;
#data =newMap<string, LWWRegister<T|null>>();constructor(id:string, state: State<T>){this.id = id;// create a new register for each key in the initial statefor(const[key, register]of Object.entries(state)){this.#data.set(key,newLWWRegister(this.id, register));}}getvalue(){const value: Value<T>={};// build up an object where each value is set to the value of the register at the corresponding keyfor(const[key, register]ofthis.#data.entries()){if(register.value !==null) value[key]= register.value;}return value;}getstate(){const state: State<T>={};// build up an object where each value is set to the full state of the register at the corresponding keyfor(const[key, register]ofthis.#data.entries()){if(register) state[key]= register.state;}return state;}has(key:string){returnthis.#data.get(key)?.value !==null;}get(key:string){returnthis.#data.get(key)?.value;}set(key:string, value:T){// get the register at the given keyconst register =this.#data.get(key);// if the register already exists, set the valueif(register) register.set(value);// otherwise, instantiate a new `LWWRegister` with the valueelsethis.#data.set(key,newLWWRegister(this.id,[this.id,1, value]));}delete(key:string){// set the register to null, if it existsthis.#data.get(key)?.set(null);}merge(state: State<T>){// recursively merge each key's register with the incoming state for that keyfor(const[key, remote]of Object.entries(state)){const local =this.#data.get(key);// if the register already exists, merge it with the incoming stateif(local) local.merge(remote);// otherwise, instantiate a new `LWWRegister` with the incoming stateelsethis.#data.set(key,newLWWRegister(this.id, remote));}}}