Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var Clock = function(id){
this.id = id;
this.clock = {};
this.clock[this.id] = 0;
};
Clock.prototype.get = function() { return data; };
Clock.prototype.update = function(data, send) {
this.clock[this.id]++;
this.data = data;
send({data: data, clock: this.clock});
};
Clock.prototype.recv = function(resp, conflict) {
// check to see if our last update was concurrent with this one
var gt = false, lt = false;
keys.forEach(function(k){
if(this.clock[k] > (resp.clock[k] || 0))
gt = true;
else
lt = true;
}.bind(this));
if(gt && lt) {
this.data = conflict(this.data, resp.data);
} else {
this.data = resp.data;
}
this.clock[this.id]++;
var keys = Object.keys(resp.clock);
// merge clocks
keys.forEach(function(k){
if(resp.clock[k] > (this.clock[k] || 0))
this.clock[k] = resp.clock[k];
}.bind(this));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment