### Lamport Clock Implementation in JavaScript Source: https://book.mixu.net/distsys/time A JavaScript implementation of a Lamport clock. It provides methods to get the current timestamp, increment the counter, and merge timestamps from other processes. Lamport clocks provide a partial order for events. ```javascript function LamportClock() { this.value = 1; } LamportClock.prototype.get = function() { return this.value; } LamportClock.prototype.increment = function() { this.value++; } LamportClock.prototype.merge = function(other) { this.value = Math.max(this.value, other.value) + 1; } ``` -------------------------------- ### Vector Clock Implementation in JavaScript Source: https://book.mixu.net/distsys/time A JavaScript implementation of a vector clock. It maintains a map of logical clocks for each node, allowing for more accurate causal ordering than Lamport clocks. Includes methods to get the current vector, increment a specific node's clock, and merge vectors from other nodes. ```javascript function VectorClock(value) { // expressed as a hash keyed by node id: e.g. { node1: 1, node2: 3 } this.value = value || {}; } VectorClock.prototype.get = function() { return this.value; }; VectorClock.prototype.increment = function(nodeId) { if(typeof this.value[nodeId] == 'undefined') { this.value[nodeId] = 1; } else { this.value[nodeId]++; } }; VectorClock.prototype.merge = function(other) { var result = {}, last, a = this.value, b = other.value; // This filters out duplicate keys in the hash (Object.keys(a) .concat(b)) .sort() .filter(function(key) { var isDuplicate = (key == last); last = key; return !isDuplicate; }).forEach(function(key) { result[key] = Math.max(a[key] || 0, b[key] || 0); }); this.value = result; }; ```