Skip to content

Instantly share code, notes, and snippets.

@thejefflarson
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejefflarson/41f2ce7c0dcf0ded2a54 to your computer and use it in GitHub Desktop.
Save thejefflarson/41f2ce7c0dcf0ded2a54 to your computer and use it in GitHub Desktop.
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