{ ringSize: number, operations: [{type, id: string}] }
1class ConsistentHash(ringSize):2 ring = sorted list of (hash, server) pairs34 function addServer(server):5 hash = hashFn(server) % ringSize6 insert (hash, server) into ring7 reassign affected keys89 function lookup(key):10 hash = hashFn(key) % ringSize11 find first server with hash >= key's hash12 (wrap around if necessary)13 return server1415 function removeServer(server):16 remove server from ring17 reassign keys to next clockwise server
1class ConsistentHash {2 private ring: Map<number, string> = new Map();3 private sortedKeys: number[] = [];45 constructor(private ringSize: number) {}67 addServer(id: string) {8 const hash = this.hash(id);9 this.ring.set(hash, id);10 this.sortedKeys = [...this.ring.keys()].sort((a, b) => a - b);11 }1213 removeServer(id: string) {14 for (const [hash, sid] of this.ring) {15 if (sid === id) { this.ring.delete(hash); break; }16 }17 this.sortedKeys = [...this.ring.keys()].sort((a, b) => a - b);18 }1920 lookup(key: string): string | null {21 if (this.sortedKeys.length === 0) return null;22 const hash = this.hash(key);23 for (const k of this.sortedKeys) {24 if (k >= hash) return this.ring.get(k)!;25 }26 return this.ring.get(this.sortedKeys[0])!;27 }2829 private hash(s: string): number {30 let h = 0;31 for (let i = 0; i < s.length; i++)32 h = (h * 37 + s.charCodeAt(i)) & 0x7fffffff;33 return h % this.ringSize;34 }35}