Last active
August 29, 2015 14:10
-
-
Save thejefflarson/41f2ce7c0dcf0ded2a54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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